我正在尝试将文本文档转换为速记,而不使用java中的任何replace()方法。我转换的其中一个字符串是“the”到“&”。问题是,我不知道包含“the”字符串的每个单词的子字符串。那么如何在不使用replace()方法的情况下替换字符串的那一部分?
例如:“他们的”将成为“& ir”,“在一起”将成为“toge& r”
这就是我的开始,
String the = "the";
Scanner wordScanner = new Scanner(word);
if (wordScanner.contains(the)) {
the = "&";
}
我只是不确定如何进行替换。
答案 0 :(得分:0)
你可以试试这个:
String word = "your string with the";
word = StringUtils.join(word.split("the"),"&");
Scanner wordScanner = new Scanner(word);
答案 1 :(得分:0)
我没有为此使用Scanner
,但您可以将每个字符读入缓冲区(StringBuilder
),直到您阅读""进入缓冲区。完成后,您可以删除该单词,然后附加要替换的单词。
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
这可以在没有使用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
答案 2 :(得分:0)
您可以使用Pattern和Matcher Regex:
Pattern pattern = Pattern.compile("the ");
Matcher matcher = pattern.matcher("the cat and their owners");
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, "& ");
}
matcher.appendTail(sb);
System.out.println(sb.toString());