Trim() String 单词完成后

Trim() String After the word is done

这里我想完成的是trim这个词完成后的字符串。但也尽量保持高效,而不是使用 StringArray.length 因为有些 String 的长度超过 2k 个字符。

int len = 140;
String str = Html.fromHtml((cureent.getTextContent().replaceAll("\n",""))).toString();
char[] StringArray;
StringArray = str.toCharArray();
for(int Index=140;Index < 150;Index++) {
    Log.d("Current Letter",String.valueOf(StringArray[Index]));
    if (String.valueOf(StringArray[Index]).equals(" ")){
        Log.d("Found E at" + String.valueOf(Index) ,"The Value is " + String.valueOf(StringArray[Index]));
    }
    item.setDescription(Html.fromHtml(cureent.getTextContent()).toString().replaceAll("\n", "").trim().substring(0,Index).replace((char) 65532, (char) 32).trim());
}

我日志中的E代表空 space

这里是日志return的一些内容。

2018-05-17 17:46:47.492 2616-2653/com.apo.rssredaer D/Found E at148: The Value is  
2018-05-17 17:46:47.495 2616-2653/com.apo.rssredaer D/Found E at141: The Value is  
2018-05-17 17:46:47.498 2616-2653/com.apo.rssredaer D/Found E at145: The Value is  

但我无法在单词后立即将其转到 trim。我仍然在中间或 trimmed 在

的任何位置得到单词 trimmed

例子。假设我有这个从我的 rss 中得到的字符串。

所以,为了纪念 antechinus 的悲惨死亡,我们给你一个小样本,例如我将使用 14 而不是 140 作为我的计数器,我将从 0 开始计数。 修剪它会对我 return:

"And so, in hon"

但凡是这样。我希望它继续发展 trim 它在

"And so, in honor"

希望我说得有道理。

好的试试这个:

int position = 0; //create a pointer
        for (int index = 140; index < 150; index++) {
            if (str.charAt(index).equals(" ")) {
                position = index;
                break; //stop the loop when you find a space

            }
        }

//create a substring from 0 to Index
 item.setDescription(Html.fromHtml(str.substring(0, position));

或者你可以这样做:

private String truncateTextMaxLength(String text, int maxLength){
    String result = text;
    int len = text.length();
    if(len < maxLength){
        return result;
    }

    int i = text.lastIndexOf(0, maxLength);
    result = text.substring(0, i);

    return result;
}

现在你可以这样调用了:

String s = truncateTextMaxLength(myText, 150);

。 请注意,对于其他代码,第 140 个和第 150 个字符之间可能没有“”。