-2

I want to parse user input in to individual characters. For example, the input

  • Hello! My name is x

Should be split in:

{"H", "e", "l", "l", "o", "!"," ", "M","y"....}

Note that I want to keep the whitespace.

I can't seem to figure out how to do this using String.split. I've tried searching for regex that would do this but all of them cut off at !.

This is the current code, I'm trying to split the string coming in from the scanner.

    public static List<String> getUserInput() {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a line of text: ");

        return Arrays.asList(scanner.next().split("")); 
}

Any help is appreciated!

4

5 回答 5

2

尝试这个:
String[] cs = s.split("");

于 2018-09-06T15:57:55.663 回答
1

我很好奇你为什么要这样做。字符串基本上可以作为数组读取charAt()。您可以使用 将字符串转换为流StringReader。您可以将字符串转换为IntStreamwithchars()codePoints()。或者,如果其内部字符数组带有toCharArray().

关于您在评论中所说的toCharArray().split()切断的内容,他们没有。您一定有错误,请向我们展示您的代码。

   public static void main( String[] args ) {
      String test = "Hello! My name is x";
      char[] chars = test.toCharArray();
      System.out.println( Arrays.toString( chars ) );
   }

这会为我打印整个字符串并且不会切断。

run:
[H, e, l, l, o, !,  , M, y,  , n, a, m, e,  , i, s,  , x]
BUILD SUCCESSFUL (total time: 0 seconds)

更新:关于您的更新,next()找到标记,默认情况下在空白处被切断。你想要nextLine()

    return Arrays.asList(scanner.next().split(""));

改成:

    return Arrays.asList(scanner.nextLine().split(""));
于 2018-09-06T16:18:53.013 回答
1

利用String.toCharArray

这将为您提供一个char[]字符串,并保留空格。

于 2018-09-06T15:53:36.800 回答
0

试试单词边界匹配器:

assertEquals(3, "a b".split("\\b").length)
于 2018-09-06T15:58:36.493 回答
0

你可以这样做:

String foo = "Hello! My name is x";

for(char c: foo.toCharArray()) {
    //do whatever you want here

    //for example
    System.out.print(c);
}

希望能帮助到你。

于 2018-09-06T16:00:04.990 回答