给定字符串之间的空格。在Java中使用数组中的每个Word

时间:2021-12-05 01:58:05

As I wrote in the title, there is a given String with space between words. I need to substring each word as an arrays' one element. I wrote something. But, It does not work as It is supposed to.

正如我在标题中所写的那样,有一个给定的字符串,字符之间有空格。我需要将每个单词子串作为数组的一个元素。我写了一些东西。但是,它不应该像它应该的那样工作。

String line =  ("<ID1> <ID2> d1|<ID3> <ID2> d2|<ID4> <ID5> d3|");

    int CountChar = 0;
    for(int i=0; i<line.length(); i++){
        if( line.charAt(i) == '|'){
                CountChar++;
        }
    }

    int[] MatrixIndex = new int[CountChar];
    for(int i=0; i<line.length(); i++){
        for(int j=0; j<MatrixIndex.length; j++){
        if( line.charAt(i) == '|'){
            CountChar++;
            System.out.println(i);
            MatrixIndex[j] = i;
        }}
    }

1 个解决方案

#1


1  

Try String#split:

尝试String#split:

String[] words = line.split(" ");

#1


1  

Try String#split:

尝试String#split:

String[] words = line.split(" ");