Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java-在x个字后分割字符串_Java_Split - Fatal编程技术网

java-在x个字后分割字符串

java-在x个字后分割字符串,java,split,Java,Split,我有一个字符串,它总是在变化,就像一个随机语句。我想做的是在10个单词之后,我想分割字符串,这样当我打印它时,它是2行 例如: String s = "A random statement about anything can go here and it won't change anything." 然后,我希望每十个单词将其拆分一次,所以在“it”之后,它会被拆分,然后看起来像这样: String[] arrayOfString; System.out.println(arrayOfSt

我有一个字符串,它总是在变化,就像一个随机语句。我想做的是在10个单词之后,我想分割字符串,这样当我打印它时,它是2行

例如:

String s = "A random statement about anything can go here and it won't change anything."
然后,我希望每十个单词将其拆分一次,所以在“it”之后,它会被拆分,然后看起来像这样:

String[] arrayOfString;
System.out.println(arrayOfString[0]); -> which prints "A random statement about anything can go here and it"
System.out.println(arrayOfString[1]); -> which prints "won't change anything."

对这方面的任何帮助都将是巨大的,谢谢

以下是代码:该代码假设您最多拆分10次,也可以将其拆分为Integer.MAX\u值

public static void main(String[] args) {
    String s = "A random statement about anything can go here and it won't change anything.";
    int spaceCount =0;
    int lastIndex=0;
    String[] stringSplitted = new String[10];//assuming the sentence has 100 words or less, you can change the value to Integer.MAX_VALUE instead of 10


    int stringLength=0;//this will give the character count in the string to be split

    for(int i=0;i<s.length();i++){
        if(s.charAt(i)==' '){   //check whether the character is a space, if yes then count the words           
            spaceCount++;// increment the count as you have encountered a word              
        }
        if(spaceCount==10){     //after encountering 10 words split the sentence from lastIndex to the 10th word. For the first time lastIndex would be zero that is starting position of the string        
            stringSplitted[stringLength++] = s.substring(lastIndex, i);
            lastIndex=i;// to get the next part of the sentence, set the last index to 10th word
            spaceCount=0;//set the number of spaces to zero to starting counting the next 10 words
            System.out.println(stringSplitted[0]);
        }
    }
    stringSplitted[stringLength++] = s.substring(lastIndex,s.length()-1);//If the sentence has 14 words, only 10 words would be copied to stringSplitted array, this would copy rest of the 4 words into the string splitted array

    for(int i=0;i<stringSplitted.length;i++){
        if(stringSplitted[i]!=null)
            System.out.println(stringSplitted[i]);//Print the splitted strings here
    }

}
publicstaticvoidmain(字符串[]args){
String s=“关于任何内容的随机语句都可以放在这里,它不会改变任何内容。”;
int spaceCount=0;
int lastIndex=0;
String[]stringSplitted=new String[10];//假设句子的字数不超过100个,可以将值改为Integer.MAX_值,而不是10
int stringLength=0;//这将给出要拆分的字符串中的字符计数

对于(inti=0;i以下是代码:代码假设您最多拆分10次,也可以将其拆分为Integer.MAX\u值

public static void main(String[] args) {
    String s = "A random statement about anything can go here and it won't change anything.";
    int spaceCount =0;
    int lastIndex=0;
    String[] stringSplitted = new String[10];//assuming the sentence has 100 words or less, you can change the value to Integer.MAX_VALUE instead of 10


    int stringLength=0;//this will give the character count in the string to be split

    for(int i=0;i<s.length();i++){
        if(s.charAt(i)==' '){   //check whether the character is a space, if yes then count the words           
            spaceCount++;// increment the count as you have encountered a word              
        }
        if(spaceCount==10){     //after encountering 10 words split the sentence from lastIndex to the 10th word. For the first time lastIndex would be zero that is starting position of the string        
            stringSplitted[stringLength++] = s.substring(lastIndex, i);
            lastIndex=i;// to get the next part of the sentence, set the last index to 10th word
            spaceCount=0;//set the number of spaces to zero to starting counting the next 10 words
            System.out.println(stringSplitted[0]);
        }
    }
    stringSplitted[stringLength++] = s.substring(lastIndex,s.length()-1);//If the sentence has 14 words, only 10 words would be copied to stringSplitted array, this would copy rest of the 4 words into the string splitted array

    for(int i=0;i<stringSplitted.length;i++){
        if(stringSplitted[i]!=null)
            System.out.println(stringSplitted[i]);//Print the splitted strings here
    }

}
publicstaticvoidmain(字符串[]args){
String s=“关于任何内容的随机语句都可以放在这里,它不会改变任何内容。”;
int spaceCount=0;
int lastIndex=0;
String[]stringSplitted=new String[10];//假设句子的字数不超过100个,可以将值改为Integer.MAX_值,而不是10
int stringLength=0;//这将给出要拆分的字符串中的字符计数

for(int i=0;i只是为了给您提供另一个解决方案。我认为这更易于阅读,因为它不需要对数组执行索引操作:

package stack;

import java.util.StringTokenizer;

 /**
 * This class can Split texts.
 */
 public class Splitter
 {

 public static final String WHITESPACE = " ";
 public static final String LINEBREAK = System.getProperty("line.separator");

 /**
  * Insert line-breaks into the text so that each line has maximum number of words.
  *
  * @param text         the text to insert line-breaks into
  * @param wordsPerLine maximum number of words per line
  * @return a new text with linebreaks
  */
  String splitString(String text, int wordsPerLine)
  {
    final StringBuilder newText = new StringBuilder();

    final StringTokenizer wordTokenizer = new StringTokenizer(text);
    long wordCount = 1;
    while (wordTokenizer.hasMoreTokens())
    {
        newText.append(wordTokenizer.nextToken());
        if (wordTokenizer.hasMoreTokens())
        {
            if (wordCount++ % wordsPerLine == 0)
            {
                newText.append(LINEBREAK);
            }
            else
            {
                newText.append(WHITESPACE);
            }
        }
    }
    return newText.toString();
   }
}
以及使用AssertJ库的JUnit测试:

package stack;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

public class SplitterTest
{
 private final Splitter sut = new Splitter();

@Test
public void splitDemoTextAfter10Words() throws Exception
{
    final String actual = sut.splitString(
        "A random statement about anything can go here and it won't change anything.", 10);

    assertThat(actual).isEqualTo("A random statement about anything can go here and it\r\n"
                                 + "won't change anything.");
}

@Test
public void splitNumerText() throws Exception
{

    final String actual = sut.splitString("1 2 3 4 5 6 7 8 9 10 11 12", 4);

    assertThat(actual).isEqualTo("1 2 3 4\r\n5 6 7 8\r\n9 10 11 12");
  }
}

我想这更容易理解,因为它不需要对数组进行索引操作:

package stack;

import java.util.StringTokenizer;

 /**
 * This class can Split texts.
 */
 public class Splitter
 {

 public static final String WHITESPACE = " ";
 public static final String LINEBREAK = System.getProperty("line.separator");

 /**
  * Insert line-breaks into the text so that each line has maximum number of words.
  *
  * @param text         the text to insert line-breaks into
  * @param wordsPerLine maximum number of words per line
  * @return a new text with linebreaks
  */
  String splitString(String text, int wordsPerLine)
  {
    final StringBuilder newText = new StringBuilder();

    final StringTokenizer wordTokenizer = new StringTokenizer(text);
    long wordCount = 1;
    while (wordTokenizer.hasMoreTokens())
    {
        newText.append(wordTokenizer.nextToken());
        if (wordTokenizer.hasMoreTokens())
        {
            if (wordCount++ % wordsPerLine == 0)
            {
                newText.append(LINEBREAK);
            }
            else
            {
                newText.append(WHITESPACE);
            }
        }
    }
    return newText.toString();
   }
}
以及使用AssertJ库的JUnit测试:

package stack;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

public class SplitterTest
{
 private final Splitter sut = new Splitter();

@Test
public void splitDemoTextAfter10Words() throws Exception
{
    final String actual = sut.splitString(
        "A random statement about anything can go here and it won't change anything.", 10);

    assertThat(actual).isEqualTo("A random statement about anything can go here and it\r\n"
                                 + "won't change anything.");
}

@Test
public void splitNumerText() throws Exception
{

    final String actual = sut.splitString("1 2 3 4 5 6 7 8 9 10 11 12", 4);

    assertThat(actual).isEqualTo("1 2 3 4\r\n5 6 7 8\r\n9 10 11 12");
  }
}
另一个解决方案:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(
            Arrays.toString(
            splitSentence(
            "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own."
            ,10)));
    }

    public static String[] splitSentence(String sentence, int amount){
        String[] words = sentence.split(" ");
        int arraySize = (int)Math.ceil((double)words.length/amount);
        String[] output = new String[arraySize];
        int index=0;
        int fullLines = (int)Math.floor((double)words.length/amount);

        for(int i=0; i<fullLines; i++){
            String appender = "";
            for(int j=0; j<amount; j++){
                appender += words[index]+" ";
                index++;
            }
            output[i] = appender;
        }
        String appender = "";
        for(int i=index; i<words.length; i++){
            appender += words[index]+" ";
            index++;
        }
        output[fullLines] = appender;
        return output;
    }

}
import java.util.*;
导入java.lang.*;
导入java.io.*;
表意文字
{
公共静态void main(字符串[]args)引发java.lang.Exception
{
System.out.println(
数组.toString(
分句(
“随机的句子也能激发其他类型项目的创造力。如果你正试图提出一个新概念、新想法或新产品,随机的句子可能会帮助你找到你可能没有考虑过的独特品质。尝试将句子融入到你的项目中可以帮助你从不同的角度看待它这比你平时独自一人要难得多。”
,10)));
}
公共静态字符串[]拆分句子(字符串句子,整数金额){
字符串[]单词=句子。拆分(“”);
int arraySize=(int)Math.ceil((double)words.length/amount);
字符串[]输出=新字符串[arraySize];
int指数=0;
int fullLines=(int)Math.floor((双)字。长度/金额);
对于(int i=0;i另一种解决方案:

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(
            Arrays.toString(
            splitSentence(
            "Random sentences can also spur creativity in other types of projects being done. If you are trying to come up with a new concept, a new idea or a new product, a random sentence may help you find unique qualities you may not have considered. Trying to incorporate the sentence into your project can help you look at it in different and unexpected ways than you would normally on your own."
            ,10)));
    }

    public static String[] splitSentence(String sentence, int amount){
        String[] words = sentence.split(" ");
        int arraySize = (int)Math.ceil((double)words.length/amount);
        String[] output = new String[arraySize];
        int index=0;
        int fullLines = (int)Math.floor((double)words.length/amount);

        for(int i=0; i<fullLines; i++){
            String appender = "";
            for(int j=0; j<amount; j++){
                appender += words[index]+" ";
                index++;
            }
            output[i] = appender;
        }
        String appender = "";
        for(int i=index; i<words.length; i++){
            appender += words[index]+" ";
            index++;
        }
        output[fullLines] = appender;
        return output;
    }

}
import java.util.*;
导入java.lang.*;
导入java.io.*;
表意文字
{
公共静态void main(字符串[]args)引发java.lang.Exception
{
System.out.println(
数组.toString(
分句(
“随机的句子也能激发其他类型项目的创造力。如果你正试图提出一个新概念、新想法或新产品,随机的句子可能会帮助你找到你可能没有考虑过的独特品质。尝试将句子融入到你的项目中可以帮助你从不同的角度看待它这比你平时独自一人要难得多。”
,10)));
}
公共静态字符串[]拆分句子(字符串句子,整数金额){
字符串[]单词=句子。拆分(“”);
int arraySize=(int)Math.ceil((double)words.length/amount);
字符串[]输出=新字符串[arraySize];
int指数=0;
int fullLines=(int)Math.floor((双)字。长度/金额);

对于(int i=0;i@RayLloy子字符串将有助于索引,但对他来说,它的单词不是字符。哦,是的!你是对的,对不起,我删除了我的评论!!但可以使用一个快速的解决方案是使用标记器或拆分空格来获取单个单词,然后将它们重新构造成十个单词字符串。但是正如@shryasarvothama所问的,你尝试了什么到目前为止,我试着用一个不同的字符替换空格,然后计算该字符显示多少次,然后再将其放入一个字符串中,但后来我遇到了一个问题,如何将之前的所有字符保存为一个字符串,带空格,其余的都保存到另一个字符串中想想这件事,我的脑子都痛了haha@RayLloy子字符串将有助于索引,但对他来说,它的单词不是字符。哦,是的!你是对的,对不起,我删除了我的评论!!但可以使用一个快速的解决方案,就是使用标记器或拆分空格来获取单个单词,然后将它们重新构造成十个单词字符串。Bu正如@ShreyasSarvothama所问的,你尝试了什么,出了什么问题?到目前为止,我尝试用不同的字符替换空格,然后计算该字符显示的次数,然后在这之后它会将其放入字符串中,但我遇到了一个问题,如何将之前的所有字符保存到一个字符串中,有空格,其余的都变成了另一个:/思考这个问题,我的大脑感到一阵剧痛哈哈,非常感谢!我现在要测试一下,非常感谢:)为什么不使用
String.split(“”)
查找字数?我看不出有任何理由像您这样查找空格。@px06谁说我们不能这样做?这只是另一种方式。但是当我们使用split(“”)时方法,我们必须再次找到第10个单词的索引,并重复一遍。最好对它进行编码,这样你就会看到差异。这里我只是逐字扫描,这样我们就有了索引计数,如果我们使用拆分方法,我们就可以