[英]Splitting string with letters and letter combinations divided by space into array in Java
I am making an app for Android, and it turned out that I do really need to "split" the string (which is actually entered by the user) to the parts and then put them into array.我正在为 Android 制作一个应用程序,结果证明我确实需要将字符串(实际上是由用户输入的)“拆分”到各个部分,然后将它们放入数组中。 The string itself is supposed to contain letter or letter combination (2 letters) and then space, letter or combination and space... for example "ab c de fg hi j".
字符串本身应该包含字母或字母组合(2 个字母),然后是空格、字母或组合和空格……例如“ab c de fg hi j”。 So for this particular example array would be like array[1]= "ab", array[2]= "c", array[3]= "de" and so on... And each letter or letter combination is supposed to get to array.
所以对于这个特定的例子,数组就像 array[1]= "ab", array[2]= "c", array[3]= "de" 等等......每个字母或字母组合都应该是进入阵列。 I've tried to use charAt with IF, but it doesn't seem to work.
我尝试将 charAt 与 IF 一起使用,但它似乎不起作用。 I'm novice to java so the only possible solution I see is to "cut" the string from the beginning and put it to array, but aren't there any other ways?
我是java新手,所以我看到的唯一可能的解决方案是从头开始“剪切”字符串并将其放入数组,但没有其他方法吗? Thanks.
谢谢。
Using split method from String使用 String 中的 split 方法
String[] myString = userString.split(" ");
Example:例子:
Input :输入:
String userString = "Hello world";
String[] myString = userString.split(" ");
Output:输出:
myString[0] = "Hello"
myString[1] = "world"
You can use the split method of String class.您可以使用 String 类的 split 方法。
String inputString = "ab c d efg h";
String[] arrayOfWords = inputString.split(" ");
for(String word:arrayOfWords) {
System.out.println(word);
}
if your inputString have any other delimeter instead of space between the words, you can use that inside the split method.如果您的 inputString 有任何其他分隔符而不是单词之间的空格,您可以在 split 方法中使用它。
Example例子
String inputString = "ab,c,d,efg,h";
String[] arrayOfWords = inputString.split(",");
for(String word:arrayOfWords) {
System.out.println(word);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.