简体   繁体   中英

Splitting a String containing special characters in to individual characters

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!

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

Use String.toCharArray

This will give you a char[] of your string, with whitespace preserved.

I'm curious why you want to do this. Strings can be read basically as arrays with charAt() . You can turn a string into a stream with StringReader . You can turn a string into an IntStream with chars() or codePoints() . Or you can just get a copy if its internal character array with toCharArray() .

Regarding something you said in the comments about toCharArray() or .split() cutting off, they don't. You must have a bug somewhere, please show us your code.

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

This prints the whole string for me and doesn't cut off.

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

Update: Regarding your update, next() finds tokens, which by default are cut off at white space. You want nextLine() .

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

Change to:

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

试试单词边界匹配器:

assertEquals(3, "a b".split("\\b").length)

You can do it as follows:

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

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

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

Hope it helps.

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