gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:57:27 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com