Java 如何在不使用replace()方法的情况下替换子字符串
我正在尝试将文本文档转换为速记,而不使用java中的任何replace()方法。我正在转换的字符串之一是“the”到“&”。问题是,我不知道包含“The”字符串的每个单词的子字符串。那么,如何在不使用replace()方法的情况下替换字符串的该部分呢 例如:“他们的”将成为“&ir”,“一起”将成为“toge&r” 这是我开始的Java 如何在不使用replace()方法的情况下替换子字符串,java,string,replace,Java,String,Replace,我正在尝试将文本文档转换为速记,而不使用java中的任何replace()方法。我正在转换的字符串之一是“the”到“&”。问题是,我不知道包含“The”字符串的每个单词的子字符串。那么,如何在不使用replace()方法的情况下替换字符串的该部分呢 例如:“他们的”将成为“&ir”,“一起”将成为“toge&r” 这是我开始的 String the = "the"; Scanner wordScanner = new Scanner(word); if (wordScanner.con
String the = "the";
Scanner wordScanner = new Scanner(word);
if (wordScanner.contains(the)) {
the = "&";
}
我只是不知道如何进行更换。您可以尝试以下方法:
String word = "your string with the";
word = StringUtils.join(word.split("the"),"&");
Scanner wordScanner = new Scanner(word);
我不知道您在这方面使用了
Scanner
,但是您可以将每个字符读入缓冲区(StringBuilder
),直到您将“the”读入缓冲区。完成此操作后,可以删除该单词,然后添加要替换的单词
public static void main(String[] args) throws Exception {
String data = "their together the them forever";
String wordToReplace = "the";
String wordToReplaceWith = "&";
Scanner wordScanner = new Scanner(data);
// Using this delimiter to get one character at a time from the scanner
wordScanner.useDelimiter("");
StringBuilder buffer = new StringBuilder();
while (wordScanner.hasNext()) {
buffer.append(wordScanner.next());
// Check if the word you want to replace is in the buffer
int wordToReplaceIndex = buffer.indexOf(wordToReplace);
if (wordToReplaceIndex > -1) {
// Delete the word you don't want in the buffer
buffer.delete(wordToReplaceIndex, wordToReplaceIndex + wordToReplace.length());
// Append the word to replace the deleted word with
buffer.append(wordToReplaceWith);
}
}
// Output results
System.out.println(buffer);
}
结果:
&ir toge&r & &m forever
&ir toge&r & &m forever
无需扫描仪,只需使用while
循环和StringBuilder
public static void main(String[] args) throws Exception {
String data = "their together the them forever";
StringBuilder buffer = new StringBuilder(data);
String wordToReplace = "the";
String wordToReplaceWith = "&";
int wordToReplaceIndex = -1;
while ((wordToReplaceIndex = buffer.indexOf(wordToReplace)) > -1) {
buffer.delete(wordToReplaceIndex, wordToReplaceIndex + wordToReplace.length());
buffer.insert(wordToReplaceIndex, wordToReplaceWith);
}
System.out.println(buffer);
}
结果:
&ir toge&r & &m forever
&ir toge&r & &m forever
您可以使用Pattern和Matcher正则表达式:
有一个名为
the
的变量并给它赋值为“the”是很奇怪的。使用String.split(the)
,然后使用和连接所有单词。为什么不使用。替换(…)?这就是它的设计目的。然后使用replaceAll
:)@Pherion:很可能是因为这是一项作业?这是如何替换扫描仪中的单词的?这对更改非常有用,但对更改单词扫描仪却没有任何作用
如果您有该怎么办?正则表达式也将匹配它。至少,我认为表达式应该是\b\b
。只是编辑了答案@npinti这是需要的,见问题的例子