我在 Java 中有如下字符串。字符串的长度未知,作为示例,它将类似于以下内容。
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;
}
谢谢
答案 0 :(得分:1)
使用 lastIndexOf()
的 2 参数版本从给定位置开始向后搜索空间。前 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
对给定长度有效
答案 1 :(得分:0)
你为什么使用这么多 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");
}
使用子字符串(开始索引,结束索引)。