//这是将字符串分割成有意义的字典单词的Java代码。 获取 StringIndexOutOfBoundException!
import java.util.*;
public class SeparateStringWords {
public static void main(String[] args) {
//segment a word into meaning full word eg. iamstudent => i am student
String str = "iamstudent";
Set < String > dict = new HashSet < String > ();
dict.add("i");
dict.add("am");
dict.add("student");
//dict is our lookup dictionary
String separated = segmentString(str, dict);
System.out.println("separated string is:" + separated);
}
static String segmentString(String str, Set < String > dict) {
if (dict.contains(str)) return str;
int len = str.length();
System.out.println(len);
for (int i = 1; i < len; i++) {
String prefix = str.substring(0, i);
if (dict.contains(prefix)) {
String suffix = prefix.substring(i, len); //StringIndexOutOfBoundException
String subSuffix = segmentString(suffix, dict);
if (subSuffix != null) {
return prefix + " " + subSuffix;
}
}
}
return null;
}
}
//已解决:感谢大家的帮助:) ..... suffix=str.substring(i,len);
最佳答案
Prefix 是比 len
短的子字符串,因为 len
是 str
的长度,而 prefix
是从 o 到 i 的子字符串,因此您必须使用 str.substring(i,len) ;
关于Java代码将字符串分割成有意义的字典单词,得到StringIndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28188723/