简体   繁体   中英

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. 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". 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. I've tried to use charAt with IF, but it doesn't seem to work. 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? Thanks.

Using split method from String

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 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.

Example

String inputString = "ab,c,d,efg,h";
String[] arrayOfWords = inputString.split(",");
for(String word:arrayOfWords) {
System.out.println(word);
}

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.

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