I am trying to hold the position of every character (A-Z) from encoded string. I am unable to find out a way to implement it in Java.
Below is one example from C++ which I am trying to rewrite in Java.
map<Character,Integer> enc = new map<Character,Integer>();
for (int i = 0; i < encoded.length(); i++)
{
enc[encoded.charAt(i)] = i;
}
Example below:
I will have a Keyword which is unique e.g., Keyword is NEW.
String will be formed by concatenating KEYWORD+Alphabets(A-Z which are not in the Keyword) e.g., NEWABCDFGHIJKLMOPQRSTUVXYZ (note that N,E and W are not repeated again in the above in the 26-Character string. Finally, I would like to hold the position of every character i.e., A-Z from the above string in bold.
If I'm understanding what youre saying, you want to map each character in a string to its index. However, Maps need a unique key for each entry, so your code wont work directly for strings which contain duplicate characters. Instead of using an Integer for each character, we'll use a List of Integers to store all the indexes which this character appears.
Here's how you would do that in java:
public static void main(String[] args) {
Map<Character, List<Integer>> charMap = new HashMap<>();
String string = "aaabbcdefg";
for (int i = 0; i < string.length(); i++) {
Character c = string.charAt(i);
if (charMap.containsKey(c)) {
List<Integer> positions = charMap.get(c);
positions.add(i);
} else {
charMap.put(c, new ArrayList<>(Arrays.asList(i)));
}
}
for (Character c : charMap.keySet()) {
System.out.print(c + ": ");
charMap.get(c).forEach(System.out::print);
System.out.println();
}
}
output:
a: 012
b: 34
c: 5
d: 6
e: 7
f: 8
g: 9
If you don't want to handle duplicates letters , you can do as follows, it’ll only keep last occurrence for each letter :
Map<Character, Integer> enc = new HashMap<>();
for (int i = 0; i < encoded.length(); i++) {
enc.put(encoded.charAt(i), i);
}
——————-
To handle duplicates char, you can hold them in a List or concatenate them in a String for example (on the second I add a filter operation to remove spaces)
public static void main (String[] args)
{
String str = "AUBU CUDU";
Map<Character, List<Integer>> mapList =
IntStream.range(0, str.length())
.boxed()
.collect(Collectors.toMap(i->str.charAt(i), i->Arrays.asList(i), (la,lb)->{List<Integer>res =new ArrayList<>(la); res.addAll(lb); return res;}));
System.out.println(mapList);
//{ =[4], A=[0], B=[2], C=[5], D=[7], U=[1, 3, 6, 8]}
Map<Character, String> mapString =
IntStream.range(0, str.length())
.boxed()
.filter(i->(""+str.charAt(i)).matches("[\\S]"))
.collect(Collectors.toMap(i->str.charAt(i), i->Integer.toString(i), (sa,sb)-> sa+sb ));
System.out.println(mapString);
//{A=0, B=2, C=5, D=7, U=1368}
}
Code Demo
Related
I have to create a HashMap that records the letters in a string and their index values in a ArrayList, so that if the HashMap is called with some string key, each related index integer is returned, and so that the map can be called by itself such that each key is shown with their indexes, For example for the string "Hello World", the map would look something like:
d=[9], o=[4, 6], r=[7], W=[5], H=[0], l=[2, 3, 8], e=[1].
I'm really confused by the requirement of the inputs as String and ArrayList, rather than chars and integers. Could you explain to me the relationship of the map to those objects, and to their components which are ultimately what are recorded as keys and values? When trying to debug, it stops processing before the map call.
The error message is:
java.lang.AssertionError: Wrong number of entries in Concordance. Expected: 5. Got: 1
Expected :1
Actual :5
But I really think I'm not grasping HashMap very well, so I'd appreciate if anyone could guide me through the basics, or provide anything educational about using HashMap, especially ones that use ArrayList.
public HashMap<String, ArrayList<Integer>> concordanceForString(String s) {
HashMap<String, ArrayList<Integer>> sMap = new HashMap<>();//create map "sMap"
char[] sArray = new char[s.length()]; //create character array, "sArray", for string conversion
ArrayList<Integer> sCharIndex = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++) {
sArray[i] = s.charAt(i); // convert string into array
}
for (int j = 0; j < sArray.length; j++){
sCharIndex.add(j); // add char indexes to index ArrayList
}
sMap.put(s, sCharIndex); //add the String and ArrayList
return sMap; // I feel like this should be sMap.get(s) but when I do, it gives me the zigzag red underline.
}
Here is a way to do it:
String input = "hello world";
Map<String, List<Integer>> letters = new HashMap<String, List<Integer>>();
// remove all whitespace characters - since it appears you are doing that
String string = input.replaceAll("\\s", "");
// loop over the length of the string
for (int i = 0; i < string.length(); i++) {
// add the entry to the map
// if it does not exist, then a new List with value of i is added
// if the key does exist, then the new List of i is added to the
// existing List
letters.merge(string.substring(i, i + 1),
Arrays.asList(i),
(o, n) -> Stream.concat(o.stream(), n.stream()).collect(Collectors.toList()));
}
System.out.println(letters);
that gives this output:
{r=[7], d=[9], e=[1], w=[5], h=[0], l=[2, 3, 8], o=[4, 6]}
EDIT - this uses a Character as the key to the map:
String input = "hello world";
Map<Character, List<Integer>> letters = new HashMap<Character, List<Integer>>();
String string = input.replaceAll("\\s", "");
for (int i = 0; i < string.length(); i++) {
letters.merge(string.charAt(i), Arrays.asList(i), (o, n) ->
Stream.concat(o.stream(), n.stream()).collect(Collectors.toList()));
}
System.out.println(letters);
Essentially, this is what you want to do.
This presumes a HashMap<String, List<Integer>>
List<Integer> sCharIndex;
for (int i = 0; i < s.length(); i++) {
// get the character
char ch = s.charAt(i);
if (!Character.isLetter(ch)) {
// only check letters
continue;
}
ch = ch+""; // to string
// get the list for character
sCharIndex = sMap.get(ch);
// if it is null, create one and add it
if (sCharIndex == null) {
// create list
sCharIndex = new ArrayList<>();
// put list in map
sMap.put(ch, sCharIndex);
}
// at this point you have the list so
// add the index to it.
sCharIndex.add(i);
}
return sMap;
A hashMap is nothing more than a special data structure that takes an object as a key. Think of an array that takes a digit as an index and you can store anything there.
A hashMap can take anything as a key (like an index but it is called a key) and it can also store anything.
Note that your key to hashMap is a String but you're using a character which is not the same. So you need to decide which you want.
HashMap<String, List<Integer>> or HashMap<Character, List<Integer>>
There are also easier ways to do this but this is how most would accomplish this prior to Java 8.
Here is a much more compact way using streams. No loops required.
Map<String, List<Integer>> map2 = IntStream
.range(0,s.length())
// only look for letters.
.filter(i->Character.isLetter(s.charAt(i)))
.boxed()
// stream the Integers from 0 to length
// and group them by character in a list of indices.
.collect(Collectors.groupingBy(i->s.charAt(i)+""));
But I recommend you become familiar with the basics before delving into streams (or until your instructor recommends to do so).
For more information check out The Java Tutorials
Check out this code :
public static void main(String []args){
//Create map of respective keys and values
HashMap<Character, ArrayList<Integer>> map = new HashMap();
String str = "Hello world"; //test string
int length = str.length(); //length of string
for(int i = 0; i < length; i++){
ArrayList<Integer> indexes = new ArrayList(); //empty list of indexes
//character of test string at particular position
Character ch = str.charAt(i);
//if key is already present in the map, then add the previous index associated with the character to the indexes list
if(map.containsKey(ch)){
//adding previous indexes to the list
indexes.addAll(map.get(ch));
}
//add the current index of the character to the respective key in map
indexes.add(i);
//put the indexes in the map and map it to the current character
map.put(ch, indexes);
}
//print the indexes of 'l' character
System.out.print(map.get('l'));
}
The code is self explanatory.
public class Array {
public static void main(String[] args) {
printSortedMap(concordanceForString("Hello world")); // r[7] d[9] e[1] w[5] H[0] l[2, 3, 8] o[4, 6]
}
public static HashMap<String, ArrayList<Integer>> concordanceForString(String s) {
HashMap<String, ArrayList<Integer>> sMap = new HashMap<>();
String str = s.replace(" ", "");
for (int i = 0; i < str.length(); i++) {
ArrayList<Integer> sCharIndex = new ArrayList<Integer>();
for (int j = 0; j < str.length(); j++) {
if ( str.charAt(i) == str.charAt(j) ) {
sCharIndex.add(j);
}
}
sMap.put(str.substring(i,i+1), sCharIndex);
}
return sMap;
}
public static void printSortedMap(HashMap<String, ArrayList<Integer>> sMap) {
for (Map.Entry<String, ArrayList<Integer>> entry : sMap.entrySet()) {
System.out.println(entry.getKey() + entry.getValue());
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
int count;
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
}
I am trying to display the occurrence of each letter (letter only) in a sentence, and I am lost. I have converted the string into a char array, but I am now lost.
For instance, if I typed the sentence: "Hello, how are you?"
The result would be:
Occurrence of h: 1
Occurrence of e: 2
Occurrence of l: 2
Occurrence of o: 3
etc..
I know I need to utilize my int count, but I am not sure how to do that. Our professor is having us use this:
c[26];
c[ch - 'a']++;
And I'm not sure where to use those for this little project.
Edit: Update
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("type the sentence you want to find the letters of");
String sentence = s.nextLine();
getLetters(sentence);
}
public static void getLetters(String sentence) {
sentence = sentence.toLowerCase();
int count[];
char ch[] = sentence.toCharArray();
for (int i = 0; i < sentence.length(); i++) {
System.out.print(ch[i]);
}
char alphabet[] = "abcdefghijklmnopqrstuvwxyz".toCharArray();
System.out.println();
}
}
Use a HashMap<Character, Integer> to keep track. The key is a unique character, and the integer counts the number of times you see it.
import java.util.HashMap;
public class J {
public static void main(String[] args) {
String string = "aaaabbbccd";
HashMap<Character, Integer> map = frequency(string);
System.out.println(map);
}
public static HashMap<Character, Integer> frequency(String string) {
int length = string.length();
char c;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
// loop thru string
for (int i = 0; i < length; i++) {
c = string.charAt(i);
// If u have already seen that character,
// Increment its count
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
// otherwise this is the first time u
// have seen it, so set count to 1
} else {
map.put(c, 1);
}
}
return map;
}
}
Output:
{a=4, b=3, c=2, d=1}
I don't see reason to use HashMap here. HashMaps are used to map some values into places in memory for faster access, using HashFunction. In this case he will have same, or very similar thing with array and this mapping function that is given to him(ch-'a') . Also, for someone who is doing this, it is maybe too soon for HashMap.
Your problem is that you haven't understood idea.
Letters in java have values (You can check ASCII table). You have 26 letters in alphabet, first one is 'a' and last is 'z'. So you want to have array of 26 elements. Every time when you have 'a' into your string, you want to increment element in place 0 in array, when you come into 'b' you want to increment element in place 1.... when you come to 'z' element 25. So, in fact with (ch-'a') you map your letter in place in array where is count of its ocurrence.
You take string, do .toLowerCase() case on it, pass it once to count letters, then print what you found.
beginner at java was asked in an interview
here i have to count the occurrence of each word in a given sentence.
for eg( "chair is equal to chair but not equal to table."
Output : chair :2,
is :1,
equal :2,
to :2,
but :1,
not :1,
table :1 )
I have written some part of the code and tried using for loop but i failed....
public static void main(String[] args)
{
int counter = 0;
String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
String[] b =a.split(" "); //stored in array and splitted
for(int i=0;i<b.length;i++)
{
counter=0;
for(int j<b.length;j>0;j--)
{
if(b[i] = b[j])
//
}
}
}
}
Use a hashmap to count frequency of objects
import java.util.HashMap;
import java.util.Map.Entry;
public class Funly {
public static void main(String[] args) {
int counter = 0;
String a = " To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
String[] b = a.split(" "); // stored in array and splitted
HashMap<String, Integer> freqMap = new HashMap<String, Integer>();
for (int i = 0; i < b.length; i++) {
String key = b[i];
int freq = freqMap.getOrDefault(key, 0);
freqMap.put(key, ++freq);
}
for (Entry<String, Integer> result : freqMap.entrySet()) {
System.out.println(result.getKey() + " " + result.getValue());
}
}
}
Quite easy since Java8:
public static Map<String, Long> countOccurrences(String sentence) {
return Arrays.stream(sentence.split(" "))
.collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()
)
);
}
I would also remove non literal symbols, and convert to lowecase before running:
String tmp = sentence.replaceAll("[^A-Za-z\\s]", "");
So your final main method for interview will be:
ppublic static void main(String[] args) {
String sentence = "To associate myself with an organization that provides a challenging job and an opportunity to provide innovative and diligent work.";
String tmp = sentence.replaceAll("[^A-Za-z\\s]", "").toLowerCase();
System.out.println(
countOccurrences(tmp)
);
}
Output is:
{diligent=1, a=1, work=1, myself=1, opportunity=1, challenging=1, an=2, associate=1, innovative=1, that=1, with=1, provide=1, and=2, provides=1, organization=1, to=2, job=1}
A simple (but not very efficient) way would be to add all the elements to a set, which doesn't allow duplicates. See How to efficiently remove duplicates from an array without using Set. Then iterate through the set and count the number of occurrences in your array, printing out the answer after each set element you check.
There are several solutions to this and I'm not going to provide you with any of them. However, I'm going to give you a rough outline of one possible solution:
You could use a Map, for example a HashMap, where you use the words as keys and the number of their occurrence as values. Then, all you need to do is to split the input string on spaces and iterate over the resulting array. For each word, you check if it already exists in the map. If so you increase the value by one, otherwise you add the word to the map and set the value to 1. After that, you can iterate over the map to create the desired output.
You need to use Map data structure which stores data in key-value pairs.
You can use the HashMap (implementation of Map) to store each word as key and their occurance as the value inside the Map as shown in the below code with inline comments:
String[] b =a.split(" "); //split the array
Map<String, Integer> map = new HashMap<>();//create a Map object
Integer counter=null;//initalize counter
for(int i=0;i<b.length;i++) { //loop the whole array
counter=map.get(b[i]);//get element from map
if(map.get(b[i]) == null) { //check if it already exists
map.put(b[i], 1);//not exist, add with counter as 1
} else {
counter++;//if already eists, increment the counter & put to Map
map.put(b[i], counter);
}
}
Using simple For loops
public static void main(String[] args) {
String input = "Table is this Table";
String[] arr1 = input.split(" ");
int count = 0;
for (int i = 0; i < arr1.length; i++) {
count = 0;
for (int j = 0; j < arr1.length; j++) {
String temp = arr1[j];
String temp1 = arr1[i];
if (j < i && temp.contentEquals(temp1)) {
break;
}
if (temp.contentEquals(temp1)) {
count = count + 1;
}
if (j == arr1.length - 1) {
System.out.println(">>" + arr1[i] + "<< is present >>" + count + "<< number of times");
}
}
}
}
This question already has answers here:
count specific characters in a string (Java)
(8 answers)
Closed 7 years ago.
I'm attempting to make my program in java count the number of letters in each word. Right now I have it counting words, not letters. Any help to get it to do letters would be great!
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.Scanner;
public class LetterTypeCount
{
public static void main(String[] args) {
// create HashMap to store String keys and Integer values
Map<String, Integer> myMap = new HashMap<>();
createMap(myMap); // create map based on user input
displayMap(myMap); // display map content
}
// create map from user input
private static void createMap(Map<String, Integer> map)
{
Scanner scanner = new Scanner(System.in); // create scanner
System.out.println("Enter a string:"); // prompt for user input
String input = scanner.nextLine();
// tokenize the input
String[] tokens = input.split(" ");
// processing input text
for (String token : tokens)
{
String letter = token.toLowerCase(); // get lowercase letter
// if the map contains the letter
if (map.containsKey(letter)) // is letter in map
{
int count = map.get(letter); // get current count
map.put(letter, count + 1); // increment count
}
else
map.put(letter, 1); // add new letter with a count of 1 to map
}
}
// display map content
private static void displayMap(Map<String, Integer> map)
{
Set<String> keys = map.keySet(); // get keys
// sort keys
TreeSet<String> sortedKeys = new TreeSet<>(keys);
System.out.printf("%nMap contains:%nKey\t\tValue%n");
// generate output for each key in map
for (String key : sortedKeys)
System.out.printf("%-10s%10s%n", key, map.get(key));
System.out.printf("%nsize: %d%nisEmpty: %b%n",
map.size(), map.isEmpty());
}
} // end class LetterTypeCount
I'm thinking I need to use the String charAt method somewhere
Might not be very elegant but:
public class LetterTypeCount
{
public static void main(String[] args) {
// create HashMap to store String keys and Integer values
Map<String, Integer> myMap = new HashMap<>();
createMap(myMap); // create map based on user input
displayMap(myMap); // display map content
}
// create map from user input
private static void createMap(Map<String, Integer> map)
{
Scanner scanner = new Scanner(System.in); // create scanner
System.out.println("Enter a string:"); // prompt for user input
String input = scanner.nextLine();
// split to words
String[] words = input.split(" ");
for (String word : words)
{
word = word.toLowerCase(); // get lowercase word
for(int i=0; i<word.length(); i++)
{
char c = word.charAt(i); //get char at position i
if (map.containsKey(c + "")) // is letter in map
{
int count = map.get(c + ""); // get current count
map.put(c + "", count + 1); // increment count
}
else
map.put(c + "", 1); // add new letter with a count of 1 to map
}
// if the map contains the letter
}
}
// display map content
private static void displayMap(Map<String, Integer> map)
{
Set<String> keys = map.keySet(); // get keys
// sort keys
TreeSet<String> sortedKeys = new TreeSet<>(keys);
System.out.printf("%nMap contains:%nKey\t\tValue%n");
// generate output for each key in map
for (String key : sortedKeys)
System.out.printf("%-10s%10s%n", key, map.get(key));
System.out.printf("%nsize: %d%nisEmpty: %b%n",
map.size(), map.isEmpty());
}
} // end class LetterTypeCount
You could create a for loop and add +1 for each letter to an array or a HashMapcontaining the letter occurance.
for(int i=0; i<= input.length(); i++){
mymap.put(input.charAt(i), myMap.get(input.charAt(i)+1));
}
But then you should define your variable myMap global and not inside your main method.
Supposing that you count latin chars only:
public int[] letters = new int['z' - 'a' + 1];
// count chars:
for (String token : tokens)
for (char c : token.toLowerCase().toCharArray())
if (c >= 'a' && c <= 'z')
letters[c - 'a']++;
// then print out counts:
for (int i = 0; i < 'z' - 'a' + 1; i++)
if (letters[i] > 0)
System.out.format("%s occurs %s time(s)\n", (char)('a' + i), letters[i]);
This looks a bit "low-level", but this is working Java code (just tested!), which uses interchangeability of chars and ints on arithmetical operations.
You can try Java 8 Stream API
Besides Java streams you also should know Java Lambda Expressions
String input = "ANY String";
Map<String, Long> map = Arrays.stream(input.split("")) // Stream String
.map(String::toLowerCase) // All letters to lower case
.filter(letter -> !letter.equals(" ")) // Remove spaces
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
You can simply use str.length() like so:
System.out.println(key.length());
Well, this is my first time get here.
I'm trying to figure out the correct way to replace number into letter.
In this case, I need two steps.
First, convert letter to number. Second, restore number to word.
Words list: a = 1, b = 2, f = 6 and k = 11.
I have word: "b a f k"
So, for first step, it must be: "2 1 6 11"
Number "2 1 6 11" must be converted to "b a f k".
But, I failed at second step.
Code I've tried:
public class str_number {
public static void main(String[] args){
String word = "b a f k";
String number = word.replace("a", "1").replace("b","2").replace("f","6").replace("k","11");
System.out.println(word);
System.out.println(number);
System.out.println();
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
System.out.println(number);
System.out.println(text);
}
}
Result:
b a f k
2 1 6 11
2 1 6 11
b a f aa
11 must be a word "k", but it's converted to "aa"
What is the right way to fix this?
Or do you have any other ways to convert letter to number and vice versa?
Thank you.
It would be good to write methods for conversion between number and letter format. I would write some code like this and use it generally instead of hard coding replace each time.
public class test {
static ArrayList <String> letter = new ArrayList<String> ();
static ArrayList <String> digit = new ArrayList<String> ();
public static void main(String[] args) {
createTable();
String test="b a f k";
String test1="2 1 6 11";
System.out.println(letterToDigit(test));
System.out.println(digitToLetter(test1));
}
public static void createTable()
{
//Create all your Letter to number Mapping here.
//Add all the letters and digits
letter.add("a");
digit.add("1");
letter.add("b");
digit.add("2");
letter.add("c");
digit.add("3");
letter.add("d");
digit.add("4");
letter.add("e");
digit.add("5");
letter.add("f");
digit.add("6");
letter.add("g");
digit.add("7");
letter.add("h");
digit.add("8");
letter.add("i");
digit.add("9");
letter.add("j");
digit.add("10");
letter.add("k");
digit.add("11");
letter.add("l");
digit.add("12");
letter.add("m");
digit.add("13");
letter.add("n");
digit.add("14");
letter.add("o");
digit.add("14");
letter.add("p");
digit.add("15");
//Carry so on till Z
}
public static String letterToDigit(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(letter.contains(individual[i])){
result+=Integer.toString(letter.indexOf(individual[i])+1)+ " ";
}
}
return result;
}
public static String digitToLetter(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(digit.contains(individual[i])){
result+=letter.get(digit.indexOf(individual[i])) + " ";
}
}
return result;
}
}
I would actually not use replace in this case.
A more generic solution would be to simply convert it to a char and subtract the char a from it.
int n = word.charAt(0) - 'a' + 1;
This should return an int with the value you are looking for.
If you want this to be an string you can easily do
String s = Integer.parseInt(word.charAt(0) - 'a' + 1);
And as in your case you are doing a whole string looping through the length of it and changing all would give you the result
String s = "";
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) != ' ') {
s = s + Integer.toString(word.charAt(i) - 'a' + 1) + " ";
}
}
and then if you want this back to an String with letters instead
String text = "";
int temp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
text = text + String.valueOf((char) (temp + 'a' - 1));
temp = 0;
} else if {
temp = (temp*10)+Character.getNumericValue(s.charAt(i));
}
}
You can just reverse the replacement:
String text = number.replace("11","k").replace("2","b").replace("6","f").replace("1","a");
Simplest solution IMO.
When adding other numbers, first replace these with two digits, then these with one.
Replace this:
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
By this:
String text = number.replace("11","k").replace("1", "a").replace("2","b").replace("6","f");
Right now, the first replace you're doing: ("1", "a")
is invalidating the last one: ("11","k")
I think you would need to store the number as an array of ints. Otherwise, there is no way of knowing if 11 is aa or k. I would create a Map and then loop over the characters in the String. You could have one map for char-to-int and one for int-to-char.
Map<Character,Integer> charToIntMap = new HashMap<Character,Integer>();
charToIntMap.put('a',1);
charToIntMap.put('b',2);
charToIntMap.put('f',6);
charToIntMap.put('k',11);
Map<Integer,Character> intToCharMap = new HashMap<Integer,Character>();
intToCharMap.put(1,'a');
intToCharMap.put(2,'b');
intToCharMap.put(6,'f');
intToCharMap.put(11,'k');
String testStr = "abfk";
int[] nbrs = new int[testStr.length()];
for(int i = 0; i< testStr.length(); i++ ){
nbrs[i] = charToIntMap.get(testStr.charAt(i));
}
StringBuilder sb = new StringBuilder();
for(int num : nbrs){
sb.append(num);
}
System.out.println(sb.toString());
//Reverse
sb = new StringBuilder();
for(int i=0; i<nbrs.length; i++){
sb.append(intToCharMap.get(nbrs[i]));
}
System.out.println(sb.toString());
This failed because the replace("1", "a") replaced both 1s with a characters. The quickest fix is to perform the replace of all the double-digit numbers first, so there are no more double-digit numbers left when the single-digit numbers get replaced.
String text = number.replace("11","k").replace("1", "a").
replace("2","b").replace("6","f");