我已经很长时间没有用 Java 编写代码了,在封锁期间我正在努力重新开始使用 Java。我遇到了这个难题,想知道是否有人可以帮助我:
1).将给定字符串拆分为给定 int 的大小
2).返回给定 int 的字符串需要分割多少次
3).没有 split 词
String random = "I want to take this and only send it at a certain number";
int random_number =12;
public int splitTheString (String random, int random_number) {
int total = 0;
int counter = 0;
String [] str = random.split(" ");
for(int i=0; i<str.length;i++)
{
total += str[i].length();
if(total < random_number){
System.out.println(str[i] + " less than 12");
counter ++;
} else {
System.out.println(str[i] + " More than 12");
counter ++;
}
System.out.println(total + " " + counter);
return counter;
} }
因此,从 main 中将调用该方法: splitTheString (random, random_number)
我正在尝试类似上面的方法,但我认为我走错了方向。有人可以帮忙吗。谢谢
编辑:
预期输入: 字符串:
1). “消息不会太长”
2). “这些消息很棒”
3). “随机消息玩起来很有趣”
4). “有些不会是 kkkk lllll pppp llll 之类的词”
5). “所有这些都将是输入类型”
预期输出,可以拆分:
1). “消息”,“不会太”,“长”=> 3
2). “这些”、“消息是”、“很棒”=> 3
3). “随机”、“消息是”、“玩起来很有趣”、“有”=> 4
4). “有些不会”、“诸如此类的词”、“kkkk lllll”、“pppp llll” => 4
5). “所有这些都将”、“成为”、“输入”=>
最佳答案
首先,调试你的代码,跟踪每次迭代中变量值的变化,我相信你可以看到哪里开始出错。
Beloved只是一个例子,以开头
static int splitter(String fullSentence, int maxChar) {
像你一样进行字符串分割,定义两个变量,一个用于像你一样的计数,另一个用于当前分割的单词,
String split = "";
int count = 0;
迭代整个句子的单词,
for (int i = 0; i < words.length; i++) {
检查 split + Words[i] 的长度是否小于 maxChar,不要忘记在单词之间添加 1 空格,
// check if words[i] is blank or empty!!!
if (split.concat(words[i]).length() + 1 <= maxChar) {
split = split.length() == 0 ? words[i] : split.concat(" " + words[i]);
}
else {
// we reached max possible chars
if (split.length() > 0) {
System.out.print(split + ", ");
count++;
}
split = words[i];
}
完成迭代后,再次检查拆分单词是否具有某些值,甚至检查它是否包含完整句子的最后一个单词,然后报告它并在必要时增加计数
System.out.println(" => " + count);
结束返回计数;
return count;
关于java - Java中按特定字符分割字符串,返回一条消息需要分割的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61197479/