简体   繁体   English

我想从文本字段中读取String句子,并将String中的每个字母与我的列表进行比较

[英]I want to read a String sentence from a Textfield and compare each letter in the String to my list

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" 我的问题是:我如何阅读我的消息,因为单个字符串可以说这是消息: "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 . 我希望能够将每个单词与我制作的字符串进行比较:因此,“ Hello World”将比较第一个字母“ H”,并将其转换为我定义的“ H”,因此将输出在JLabel或其他任何形式中,如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. 我认为您需要将字母(A = ...,B = ...,H = ...)存储到Map ,然后遍历输入的字母(可以使用toCharArray()从输入字符串中toCharArray() ),如果Map包含字母作为键,则输出相应的值。 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: 一旦有了一个String (我们将其称为myString ),就可以像这样遍历字母:

for (final char c : new StringIterator(myString)) { // Do something with each character (c) } for(final char c:new StringIterator(myString)){//对每个字符(c)进行操作}

\n

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.toCharArray()获得一个字符数组,您可以在其中单独访问每个字符。

String[] charArray = userInput.toCharArray();
for (int i = 0; i < charArray.length; i++)
{
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM