从字符串 java 中拆分文本

我有一个长文本,我想分成几个小句子。以下是我的文本。

我尝试在字符串方法中计算单词?但那里给出的解决方案是拆分字符串 return trim.split("\\s+").length;。在我的文字中,我没有任何空格。

社会主义,即字,臭,粗心,国会,他们的,战略,到目前为止,在人民中,社会主义,yadavunna,钦佩,剥削,做,其,移动,ani,即,o,字,下降,上, 记住。

我知道 split() 用于拆分字符串。但我不知道如何分割上面的文本,因为没有空格或任何其他正则表达式可以分割。

以下代码用于拆分文本

String string = "1234,56,789,10,1111111,1111112,12";

char[] ch = string.toCharArray();  

int comma_limit = 3;

int comma_count = 0;

for(int i=0;i<ch.length;i++) 

if (ch[i] == ',') {

    comma_count = comma_count + 1;


if (comma_count % comma_limit == 0)

{

ch[i] = '.';

System.out.println(ch);


     }

  }


一只名叫tom的猫
浏览 163回答 4
4回答

杨魅力

使用带有逗号分隔符的 split 方法,它将返回分隔字符串的数组,然后使用 length 方法,获取其大小System.out.println(yourString.split(",").length);

PIPIONE

static IEnumerable<string> Split(string str, int chunkSize){&nbsp; &nbsp; return Enumerable.Range(0, str.Length / chunkSize)&nbsp; &nbsp; &nbsp; &nbsp; .Select(i => str.Substring(i * chunkSize, chunkSize));}您需要检查极端情况。

守候你守候我

一旦您将在循环中获得 3 个字符串,请检查此项,您可以增加拆分计数..&nbsp; &nbsp; public void splitStr(){&nbsp; &nbsp; &nbsp; &nbsp; String str = "";&nbsp; &nbsp; &nbsp; &nbsp; String[] split_str = str.split(",");&nbsp; &nbsp; &nbsp; &nbsp; int len = split_str.length;&nbsp; &nbsp; &nbsp; &nbsp; int split_len = len/3;&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i< len; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String f1 ="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i == split_len){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // first string&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; f1 = split_str[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // You will get 3&nbsp; &nbsp;f1 strings&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; split_len += split_len+ i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

慕雪6442864

我对你的要求感到困惑。假设您希望实现某种自动换行,您可以执行以下操作。这可能不是最好的方法,但它是一种方法。divideString("This is my sentence! I would like to split this into 3 Strings with about the same length.", 3);public static void divideString(String raw, int numberOfDivides) {&nbsp; &nbsp; int charsPerString = raw.length()/numberOfDivides;&nbsp; &nbsp; String[] refined = new String[charsPerString];&nbsp; &nbsp; for(int i=1; i < (raw.length()/charsPerString)+1; i++) {&nbsp; &nbsp; &nbsp; &nbsp; refined[i] = raw.substring((charsPerString*i)-charsPerString, charsPerString*i);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(refined[i]);&nbsp; &nbsp; }}这将输出以下内容:This is my sentence! I would like to split this into 3 Strings with about the same length.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java