带有子串

时间:2017-02-19 13:48:39

标签: java android

这是我的代码:

String s = word;
String[] split = s.split(Dictionary.searchTerm);
String s1 = split[0];
String s2 = split[1];
String cut1 = "...";
String cut2 = s2.substring(0, 20);

我从行java.lang.StringIndexOutOfBoundsException: length=17; regionStart=0; regionLength=20

引起String cut2 = s2.substring(0, 20);

我尝试做的是,例如,这是原始字符串s

谷歌
Android的
Gmail的
的Youtube
苹果
iOS版
苹果
微软
视窗

searchTerm是Youtube,因此所需的字符串是

... Youtube Apple

如何解决这个问题?基本上我想要实现的是将searchTerm之前的字符串替换为...并在searchTerm之后添加字符串的部分部分。

2 个答案:

答案 0 :(得分:1)

您的要求可以通过以下代码实现,而不是经过严格测试。

    String s = "Google     Android    Gmail    Youtube     Apple    iOS     Mac     Microsoft   Hewlett packard      Windows";

            String[] keywords = s.split("\\s+");

            String searchTerm = "Youtube";

            String endText = "";

            for(int index = 0; index < keywords.length; index++) {
                if(keywords[index].contentEquals(searchTerm)) {
                    if(index != (keywords.length - 1)) {
                        endText = endText + "..." + " " + searchTerm + " " + keywords[index + 1];
                    } else {
                        endText = endText + "..." + " " + searchTerm + " " + keywords[0];
                    }
                }
            }

// Here the endText would be: "... Youtube Apple"

答案 1 :(得分:0)

抛出StringOutOfBoundsException是因为你假设cut2在索引20处结束,而你的字符串不是那么长。您需要计算s2的长度,而不是硬编码20。如果您期望s2的长度为21,那么您可能需要检查以确保它存储您认为存储的内容。

相关问题