aspose file tools*
The moose likes Java in General and the fly likes String in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "String in java" Watch "String in java" New topic
Author

String in java

Tarik Ansari
Ranch Hand

Joined: Dec 31, 2008
Posts: 50
Hi All,
i had a question which was asked in an interview to analyse my problem solving ability.

Snippet:
String a ="abcba";

Based on the occurance of the alphabets it should append the appropriate numbers before the alphabets.

So String a ="abcba" should be replaced by "2a2bc".

Please suggest a snippet which will return the result for me.

Thanks in advance
Lester Burnham
Rancher

Joined: Oct 14, 2008
Posts: 1337
Assuming we're talking about lowercase ASCII characters only, the solution could involve a "int[] letterCount = new int[26]" field.

For a more generalized problem, a "Map<Character,Integer> letterCount = new HashMap<Character,Integer>" would work.

In either case two loops would be necessary - one to count the letters, and one to create the resulting string.
Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 117
You should be taking each character and put it to a map and raise "value" every time you find occurrence of key example
iterative representation of String s will be

<a,1>
<b,1>
<c,1>

<a,2>
<b,2>
<c,1>


and than print this in desired way.

Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19557
    
  16

Lester Burnham wrote:For a more generalized problem, a "Map<Character,Integer> letterCount = new HashMap<Character,Integer>" would work.

Or:
- a LinkedHashMap if insertion order should be used
- a TreeMap if alphabetical order should be used


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String in java
 
Similar Threads
Puzzle
Doubt Regarding Java Script
Possessive Quntifiers
convert long to string
to get an arraylist containing only non-alphabet strings