I want to read a String sentence from a Textfield and compare each letter in the String to my list of already made strings which look like this:
A = 123f;
B = 221d;
H = 2333gg;
And so on..
My question is: how can i read my message as individual strings lets say this is the message: "Hello World"
i want to be able to compare every word to my strings that i have made: so "Hello World" it would compare the first letter "H" and it would make it into what i defined "H" to be, So it would output in a JLabel
or anything else as 2333gg
.
Thank you in advance!
I think you need to store your letters (A = ..., B = ..., H = ...) into a Map
, then you iterate through the input letters (that you can get from the input string using toCharArray()
), and if the Map
contains the letter as a key, you output the corresponding value. Something like this:
Map<Character, String> lettersMap = new HashMap<Character, String>();
lettersMap.put(Character.valueOf('A'), "123f");
lettersMap.put(Character.valueOf('B'), "221d");
lettersMap.put(Character.valueOf('H'), "2333gg");
String input = "Hello world";
StringBuffer sb = new StringBuffer();
char[] inputLetters = input.toCharArray();
for (int i = 0; i < inputLetters.length; i++) {
Character letter = Character.valueOf(inputLetters[i]);
if (lettersMap.containsKey(letter))
sb.append(lettersMap.get(letter));
}
System.out.println(sb.toString());
Once you have a String
(let's call it myString
), you can iterate through the letters like so:
for (final char c : new StringIterator(myString)) { // Do something with each character (c) }
Does that help?
Edit: I'm SO sorry - I was using a non standard library in a piece of code and forgot.
How about:
for (int i = 0; i < myString.length(); i++)
{
char c = myString.charAt(i);
//Process char
}
You can use String.toCharArray()
to get an array of chars, where you can access each char individually.
String[] charArray = userInput.toCharArray();
for (int i = 0; i < charArray.length; i++)
{
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.