如何使用Java根据长度和空间分割字符串
我在Java中有一个字符串,如下所示。字符串的长度未知,作为一个示例,它如下所示如何使用Java根据长度和空间分割字符串,java,split,Java,Split,我在Java中有一个字符串,如下所示。字符串的长度未知,作为一个示例,它如下所示 String str = "I love programming. I'm currently working with Java and C++." 对于某些要求,我希望获得前15个字符。接下来是30、45、70个字符。一旦字符串被拆分,如果名称没有意义,则应将其从最近的空间拆分。对于上述示例,输出如下所示 String strSpli1 = "I love "; //S
String str = "I love programming. I'm currently working with Java and C++."
对于某些要求,我希望获得前15个字符。接下来是30、45、70个字符。一旦字符串被拆分,如果名称没有意义,则应将其从最近的空间拆分。对于上述示例,输出如下所示
String strSpli1 = "I love "; //Since 'programming' is splitting it was sent to next split
String strSpli2 = "programming. I'm currently ";//Since 'working' is splitting it was sent to next split
String strSpli3 = "working with Java and C++.";
请帮助我实现这一目标
针对任何有此类需求的人的更新答案
String str = "I love programming. I'm currently working with Java and C++.";
String strSpli1 = "";
String strSpli2 = "";
String strSpli3 = "";
try {
strSpli1 = str.substring(15);
int pos = str.lastIndexOf(" ", 16);
if (pos == -1) {
pos = 15;
}
strSpli1 = str.substring(0, pos);
str = str.substring(pos);
try {
strSpli2 = str.substring(45);
int pos1 = str.lastIndexOf(" ", 46);
if (pos1 == -1) {
pos1 = 45;
}
strSpli2 = str.substring(0, pos1);
str = str.substring(pos1);
try {
strSpli3 = str.substring(70);
int pos2 = str.lastIndexOf(" ", 71);
if (pos2 == -1) {
pos2 = 45;
}
strSpli3 = str.substring(0, pos2);
str = str.substring(pos2);
} catch (Exception ex) {
strSpli3 = str;
}
} catch (Exception ex) {
strSpli2 = str;
}
} catch (Exception ex) {
strSpli1 = str;
}
谢谢使用2参数版本的
lastIndexOf()
从给定位置开始向后搜索空格。前15个字符的示例:
int pos = str.lastIndexOf(" ", 16);
if (pos == -1) {
pos = 15;
}
String found = str.substring(0, pos);
str = str.substring(pos+1);
这缺少一些检查,例如确保字符串至少以15个字符开头,或者确保pos+1
对于给定长度有效
建议看一看为什么要使用这么多try-catch?试试这个
public class MyClass {
public static void main(String args[]) {
String str = "I love programming. I'm currently working with Java and C++.";
String strSpli1 = "";
String strSpli2 = "";
String strSpli3 = "";
strSpli1 = str.substring(0, 7);
strSpli2 = str.substring(7, 33);
strSpli3 = str.substring(34, str.length());
System.out.println(strSpli1+"\n");
System.out.println(strSpli2+"\n");
System.out.println(strSpli3+"\n");
}
使用子字符串(开始索引、结束索引)。您自己尝试过哪些内容但不起作用?您可以分享您迄今为止尝试过的内容吗?您可以使用String类的
indexOf
方法查找下一个空格
字符,这些字符接近长度
的30,45,70,并使用子字符串
@Nisanth Reddy我已经用我尝试过的代码更新了这个问题。@AbRe您不应该只根据长度进行拆分。试着一步一步地做。以第一个长度拆分30
。然后检查这个子串,如果它在中间打破了一个单词,你就已经分裂了。如果它正在打断单词,则使用indexOf
在字符串中查找两个最近的```。一旦有了这两个索引,就可以决定选择哪一个并更新新的子字符串。然后你可以继续下一个length
你想要的,并重复相同的过程,直到你到达字符串的末尾。你如何判断“名称是否没有意义”?因为我不知道字符串的长度。如果长度小于15,它将抛出一个例外。使用此选项了解长度的多少,str.length()你的意思是你的输入是一般的还是动态的?动态输入,有时它的长度将小于15