Matcher not finding overlapping words?

前端 未结 4 454
猫巷女王i
猫巷女王i 2021-01-28 08:05

I\'m trying to take a string:

String s = \"This is a String!\";

And return all 2-word pairs within that string. Namely:

{\"this         


        
4条回答
  •  借酒劲吻你
    2021-01-28 08:35

    Run a for loop from i = 0 to the number of words - 2, then the words i and i+1 will make up a single 2-word string.

    String[] splitString = string.split(" ");
    for(int i = 0; i < splitString.length - 1; i++) {
        System.out.println(splitString[i] + " " + splitString[i+1]);
    }
    

    The number of 2-word strings within a sentence is simply the number of words minus one.

    int numOfWords = string.split(" ").length - 1;
    

提交回复
热议问题