java - 在特定索引的文本中嵌入单词

标签 java regex

我有一个文本,我想在特定索引处的文本中包含一个词。我设法找到了需要包含新词的文本索引。但是,我找不到在嵌入过程中使用该索引的方法。我尝试按如下方式使用替换功能:

newSentence = oldSentence.replace(oldWord, (oldWord+" "+newWord));

问题是此方法替换了所有出现的 oldWord,而我只想更改特定索引处的单词。

我很感激任何建议

最佳答案

您可以使用 StringBuilder#replace() .它可以像这样替换给定 String 的一部分:

StringBuilder sb = new StringBuilder(oldSentence);
sb.replace(wordPos, newWord.length()-1, newWord);
newSentence = sb.toString();

来自javadoc :

public StringBuilder replace(int start,
                    int end,
                    String str)

Replaces the characters in a substring of this sequence with characters in the specified String. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the sequence if no such character exists. First the characters in the substring are removed and then the specified String is inserted at start. (This sequence will be lengthened to accommodate the specified String if necessary.)

关于java - 在特定索引的文本中嵌入单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16725514/

相关文章:

java - JList - 从点击中获取值(value)

regex - 实现 Google 搜索运算符

objective-c - Cocoa/Objective-C 中的简单字符串解析 : parsing a command line into command and arguments

java vector 作用域

java - 抛出并捕获异常,还是使用instanceof?

java - Minimax 算法中 alpha/beta 的起始值是多少?

Java 小程序和 64 位整数

标签之间的 JavaScript RegEx 无法使用 console.log 工作

json - Apache NiFi 拆分 JSON 根数组

javascript - 将字符串转换为方法参数,特别是在 console.log 中