java 拆分没有分隔符的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13453075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:47:40  来源:igfitidea点击:

Splitting a string with no delimiter

javaarraysstringsplit

提问by Adegoke A

I want to split a string like "My dog" into an array of:

我想将像“My dog”这样的字符串拆分为以下数组:

| M | y | space char will be in here | D | o | g |

Here is my code:

这是我的代码:

String []in_array;
    input = sc.next();  
in_array = input.split(""); //Note this there is no delimiter 

for(int k=1; k < in_array.length; k++){
    System.out.print(" "+in_array[k]);
}

EDIT:

编辑:

It only prints out "My"

它只打印出“我的”

回答by Aleksander Blomsk?ld

java.lang.String has a toCharArray()that does exactly that.

java.lang.String 有一个toCharArray()就是这样做的。

回答by Peter Lawrey

If all you see if "My", that is all you have in your inputstring. Did you use Scanner.next() ?

如果您只看到“我的”,那么这就是您的input字符串中的全部内容。你用过 Scanner.next() 吗?

for(String s : "My dog".split(""))
    System.out.println(s);

prints

印刷

{empty line}
M
y

d
o
g

回答by Bohemian

You only need one line of code for this:

为此,您只需要一行代码:

String[] arr = input.split("(?<=.)");

The regex says to split afterevery character, so unlike splitting on blank, you don't get an initial blank element from the split.

正则表达式表示每个字符拆分,因此与在空白上拆分不同,您不会从拆分中获得初始空白元素。

回答by Saurabh

Try Following Java code

尝试遵循 Java 代码

String sourceString="My Dog";
char[] varArr = sourceString.trim().toCharArray();
for (char c : varArr) {
   System.out.print(c+" | ");
}