Java代码将字符串分割成有意义的字典单词,得到StringIndexOutOfBoundException

标签 java string dictionary

//这是将字符串分割成有意义的字典单词的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 短的子字符串,因为 lenstr 的长度,而 prefix 是从 o 到 i 的子字符串,因此您必须使用 str.substring(i,len) ;

关于Java代码将字符串分割成有意义的字典单词,得到StringIndexOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28188723/

相关文章:

java - 替换正在运行的 Java 应用程序中的证书

java - java中的Mark()/重置BufferedReader

html - 如何允许在传递给 HTML 值属性的字符串中使用双引号和单引号?

python - 在 Python 中优先使用字典而不是对象

python - 从 csv 文件中读取数据,同时监视文件夹中的更改

java - 创建sql查询的方法?

java - 迷你搜索引擎程序主方法的用户输入

python - 如何从字符串中提取简单的数字表达式数字?

string - Go 中对字符串字面量的引用

python - 删除列表中的多个词典