[英]Java convert string to string array by spaces
I would like to convert string to string array.. I have done something like this: 我想将字符串转换为字符串数组。
String name = "name";
String[] letters = name.split("(?<=.)");
System.out.println("letters = " + Arrays.toString(letters));
But now I want something like this: 但是现在我想要这样的东西:
String name = "John Mark Lester Andrew Todd";
To print array like this: 要像这样打印数组:
[John, Mark, Lest, Andrew, Todd]
So I want to look for spaces in my string and then put them into a string array. 因此,我想在字符串中查找空格,然后将其放入字符串数组中。 Do you have ideas to do this?
您有这样做的想法吗? Help is much appreciated.
非常感谢您的帮助。 Thanks.
谢谢。
您只需在whitespace
上将字符串split()
即可。
String[] words = name.split(" ");
What ever criteria or letter on the basis of which a string is to be split,that need to be provided under 需要在以下位置提供依据的标准或字母:
string.split(" ");
so,u can try using these updated code::: 因此,您可以尝试使用这些更新的代码:::
String name = "John Mark Lester Andrew Todd";
String[] letters = name.split(" ");
System.out.println("letters = " + Arrays.toString(letters));
and the ouput will be:: 输出将是:
letters = [John, Mark, Lester, Andrew, Todd]
And for better understanding for splitting the strings in java,you can go to this link. 为了更好地理解在Java中拆分字符串,可以转到此链接。 http://www.tutorialspoint.com/java/java_string_split.htm
http://www.tutorialspoint.com/java/java_string_split.htm
You can use split()
and create an array. 您可以使用
split()
并创建一个数组。
String name = "John Mark Lester Andrew Todd";
String[] names=name.split(" ");
也许您可以使用StringTokenizer
The most flexible is to split on all whitespace: 最灵活的方法是在所有空格上分割:
String names = "John \t\t Mark Lester \n Andrew Todd \r";
System.out.println(Arrays.toString(names.split("\\s+")));
Outputs: 输出:
[John, Mark, Lester, Andrew, Todd]
\\\\s+
is regex for "any length of any whitespace characters". \\\\s+
是“任何空白字符的任何长度”的正则表达式。 Similarly if you only care about spaces: 同样,如果您只关心空格:
String names = "John Mark Lester Andrew Todd ";
System.out.println(Arrays.toString(names.split(" +")));
(Outputs same as above.) (输出与上面相同。)
Of course both of those will split single spaces too. 当然,这两个都将分割单个空格。
You can use : 您可以使用 :
String values=Arrays.toString(name.split(" "));
or
String values[] = name.split("\\s")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.