如何取1至3个字符串的字符串?

时间:2014-03-27 02:02:42

标签: java regex

如何从1到3个单词中取出字符串?每行最多3个字

例如:

The Pacific Ocean is the largest of the Earth's oceanic divisions

输出:

The pacific Ocean
is the largest
of the Earth's
oceanic divisions

尝试:

    String[] sequences = {""};
    int numberOfSequnces = (int)words.length/3;

    for(int i=0;i<words.length;i++)
    {
        String word=words[i];
        String sequnce=word;
        for(int m=i+1;m<numberOfSequnces;m++)
        {
            for(int g=m;g<3;g++)
            sequnce +=words[g];
        }

        sequences[i]=sequnce;
    }

我遇到的问题: 数组超出索引。我认为是因为单词[g]

4 个答案:

答案 0 :(得分:3)

你的&#34;输出&#34;实际上意味着如果只是意味着在控制台上打印出来:

String[] words = line.split(" ");
for(int i = 0; i < words.length; i++) {
    System.out.print(words[i]);
    if ((i + 1) % 3 != 0) {
        System.out.print(" ");
    } else {
        System.out.println();
    }
}

答案 1 :(得分:2)

这将完全打印您发布的输出,

String line = "The Pacific Ocean is the largest of the "
    + "Earth's oceanic divisions"; // <-- The line.
String[] words = line.split(" ");
int count = 0; // <-- A word count.
for (int i = 0; i < words.length; i++) {
  String word = (words[i] != null) ? words[i]
      .trim() : ""; // <-- Ternary, check for null and consecutive spaces.
  if (word.length() > 0) { // <-- make sure there is a word.
    if (count > 0) { // <-- check the word count.
      if (count % 3 == 0) { // <-- Is it divisible by 3? Newline.
        System.out.println();
      } else { // <-- not divisible by 3, space.
        System.out.print(' ');
      }
    }
    count++; // <-- There is a word, add one to the count.
    System.out.print(word); // <-- print it.
  }
}

答案 2 :(得分:1)

您可以使用正则表达式执行此操作:

String sentence = "The Pacific Ocean is the largest of the Earth's oceanic divisions";
sentence = sentence.replaceAll("([^\\p{javaWhitespace}]*\\p{javaWhitespace}){3}", "$0"+System.getProperty("line.separator"));
System.out.println(sentence);

答案 3 :(得分:0)

使用此模式/(\S+\s+\S+\s+\S+)\s+/g
并替换为$1\n
Demo