wood burning stoves 2.0
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "String in java" Watch "String in java" New topic

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.

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

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: 118
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



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

Joined: Oct 27, 2005
Posts: 20279

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

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

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: String in java
It's not a secret anymore!