Reputation: 27
I'm trying to split a string into two-character blocks. I then want to find the position of the two characters in a character array. How do I do this in Java
for (int i = 0; i < message.length(); i += 2) {
// Split the message into substrings of 2
String splitMessage = message.substring(i,+ i+2);
System.out.println(splitMessage);
//
for (int j = 0; j < splitMessage.length(); j++) {
int plainTxtCh = charSet.indexOf(splitMessage.charAt(j));
System.out.println(plainTxtCh);
}
which returns
xy
23
24
ed
4
3
dd
3
3
what I want to do is pair the two numbers together. So for example after xy, I would have one integer '2324' instead of two seperate integers. Thanks.
EDIT: I want every two letters to be grouped into one integer according to their position in the alphabet string I made, so 'ed' = 43 dd='33' etc.
Upvotes: 1
Views: 2202
Reputation: 3836
Maybe you should try this:
String charset = "abc";
String message = "abcabcabca";
char[] msgArr = message.toCharArray();
for (int i = 0; i < msgArr.length; i += 2) {
System.out.println(msgArr[i] + "" + (i == msgArr.length - 1 ? "" : msgArr[i + 1]));
System.out.println(charset.indexOf(msgArr[i]) + "" + (i == msgArr.length - 1 ? "" : charset.indexOf(msgArr[i + 1])));
}
The output is:
ab
01
ca
20
bc
12
ab
01
ca
20
Works with both odd and even message length :)
Upvotes: 0
Reputation: 161
You can use Pattern. Remember that when you'd like to find digits in your string, use:
Matcher m = Pattern.compile("\\d+").matcher(yourString);
Or you can delete "enter" between digits. Use this pattern to find you divided digits:
Pattern p = Pattern.compile("(\\d+)(\\s)(\\d+)");
Upvotes: 0
Reputation: 1892
Change the inner for loop to this following:
for (int j = 0; j < splitMessage.length(); j++){
int plainTxtCh = charSet.indexOf(splitMessage.charAt(j));
System.out.print(plainTextCh);
}
System.out.println();
Upvotes: 1