I have given a string "my1kiran4name2is3" and my expected output is "my name is kiran"
Explanation1
my - 1
kiran - 4
name - 2
is - 3
I have to arrange the words based on the numbers. the string only contains numbers from 1 to 9.
So my output is "my name is kiran"
been trying to solve this problem from past two days but not finding any way just started learning java, any kind of help would be appreciated.
CodePudding user response:
As a heads-up that as a reviewer, I wouldn't approve the next code because it's hard to read and maintain. But in case there is someone like me and likes regexes and streams:
String string = "my1kiran4name2is3";
Map<Integer, String> map =
Arrays.asList(string
.split("(?<=\\d)"))
.stream()
.map(s -> s.split("(?=\\d)"))
.collect(Collectors.toMap((e -> Integer.parseInt(e[1])), e -> e[0]));
string = map
.values()
.stream()
.collect((Collectors.joining(" ")));
System.out.println(string);
A little explanation:
- (?<=\d) is positive lookbehind. We split the String if the value before the match is a digit. So as a result we have (my1, kiran4, name2, is3)
- (?=\d) is positive lookahead we map the String if the Value ahead is a number. So as a result we have (my 1, kiran 4, name 2, is 3)
CodePudding user response:
Another solution, just for fun:
Pattern re = Pattern.compile("([^0-9] )([0-9] )");
String input = "my1kiran4name2is3";
Map<Integer,String> words = new TreeMap<>();
Matcher matcher = re.matcher(input);
while (matcher.find()) {
words.put(Integer.valueOf(matcher.group(2)), matcher.group(1));
}
String output = String.join(" ", words.values());
System.out.println(output);
CodePudding user response:
You can use StringBuilder
and Map
to solve your problem:
String str = "my1kiran4name2is3";
Map<Integer, String> map = new HashMap<>();
StringBuilder key = new StringBuilder();
StringBuilder value = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
key.append(c);
} else {
if (key.length() > 0) {
map.put(Integer.valueOf(key.toString()), value.toString());
key.setLength(0);
value.setLength(0);
}
value.append(c);
}
}
map.put(Integer.valueOf(key.toString()), value.toString());
String response = String.join(" ", map.values()); // my name is kiran
The idea here is to loop over all the characters and check if digit or not, then in the end store the number as a key in the map and the string as a value.