java 在Java中不使用replace替换字符串中的单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31085200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace words in a string without using replace in Java
提问by LBS_Me
I am trying to replace all occurrences of a word in a string. However with this code I can only find the first occurrence of it and replace it. Is there any way to expand this code to replace the words in the entire string? I am attempting to do this without using the replace built in methods in Java since I already know how to use those function, I was wondering if there was another way to go about it.
我正在尝试替换字符串中所有出现的单词。但是,使用此代码,我只能找到它的第一次出现并替换它。有没有办法扩展这段代码来替换整个字符串中的单词?我试图在不使用 Java 中的替换内置方法的情况下执行此操作,因为我已经知道如何使用这些函数,我想知道是否还有其他方法可以解决此问题。
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord + partAfter;
}
回答by laune
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord + replace(old, newWord, partAfter );
}
However, it's more efficient to collect the bits and pieces in a StringBuilder.
但是,在 StringBuilder 中收集点点滴滴的效率更高。
public static String replace(String oldStr, String newStr, String input) {
StringBuilder sb = new StringBuilder();
int i;
int prev = 0;
while( (i = input.indexOf(oldStr, prev)) >= 0 ){
sb.append( input.substring(prev, i) ).append( newStr );
prev = i + oldStr.length();
}
sb.append(input.substring(prev));
return sb.toString();
}
回答by Erwin Bolwidt
There is a simple solution that uses recursion. Once you have replaced the word for the first time in the string, you can then replace the word in the partAfter
part of the string by calling the replace method again:
有一个使用递归的简单解决方案。第一次替换字符串中的单词后,您可以partAfter
通过再次调用 replace 方法替换字符串部分中的单词:
public static String replace(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0) {
return input;
}
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return partBefore + newWord +
replace(old, newWord, partAfter); // <<-- Note recursion here
}
This only changes one line from your original source.
这只会更改原始来源的一行。
回答by T.J. Crowder
First, you need a loop of some kind. Probably a while
.
首先,您需要某种循环。大概是一个while
。
In the loop, since you're replacing the "old" string, you could just keep looping until you don't find it anymore. But if you want to avoid re-searching the first part of the string, or if you want to allow the replacement to contain the string it's replacing (without then looping infinitely), then once you've done each replacement, use String#indexOf(String str, int fromIndex)
, which lets you continue from the middle of the string.
在循环中,由于您要替换“旧”字符串,因此您可以继续循环直到找不到它为止。但是如果你想避免重新搜索字符串的第一部分,或者如果你想让替换包含它正在替换的字符串(而不是无限循环),那么一旦你完成了每个替换,使用String#indexOf(String str, int fromIndex)
,这让你从字符串的中间继续。
回答by Eran
First of all, don't use new
for a variable name. It's a reserved word.
首先,不要new
用于变量名。这是一个保留字。
Second of all, in order to replace multiple occurences, you should have a loop.
其次,为了替换多次出现,你应该有一个循环。
Finally, it's better to create the new String using a StringBuilder, not String concatenation.
最后,最好使用 StringBuilder 创建新的 String,而不是 String 连接。
This is untested, but something like this should work:
这是未经测试的,但这样的事情应该有效:
public static String replace(String oldStr, String newStr, String input) {
int i = input.indexOf(oldStr);
if (i < 0) {
return input;
}
StringBuilder buffer = new StringBuilder();
int prev = 0;
while (i >= 0) {
String partBefore = input.substring(prev, i);
prev = i + oldStr.length();
buffer.append(partBefore);
buffer.append(newStr);
i = input.indexOf(oldStr, i + oldStr.length());
}
buffer.append(input.substring(i+oldStr.length()));
return buffer.toString();
}
回答by Rajesh
Use Recursion:
使用递归:
public static String replaceAll(String old, String newWord, String input) {
int i = input.indexOf(old);
if (i < 0)
return input;
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
return replaceAll(old, newWord, partBefore + newWord + partAfter);
}
Use do-While and go on replacing words:
使用 do-While 并继续替换单词:
public static String replaceAll(String old, String newWord, String input) {
boolean loop = true;
do {
int i = input.indexOf(old);
if (i > 0) {
String partBefore = input.substring(0, i);
String partAfter = input.substring(i + old.length());
input = partBefore + newWord + partAfter;
} else
loop = false;
} while (loop);
return input;
}
回答by Saad Mirza
Here is the Code
这是代码
import java.util.Scanner;
public class replacechar {
String line;
String s = "";
char from ;
char to ;
public replacechar()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter The String");
line = scan.nextLine();
System.out.println("Enter The Character you want to changer");
from = scan.nextLine().charAt(0);
System.out.println("Enter the Character you want to replace with");
to = scan.nextLine().charAt(0);
replacecharacter(from,to);
}
public void replacecharacter(char f,char t)
{
for(int i =0;i< line.length();i++)
{
if(line.charAt(i) == f)
{
s += t;
}
else
{
s += line.charAt(i);
}
}
System.out.println(s);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
replacechar obj = new replacechar();
}
}
回答by Faisal Khan
Not too sure if OP is still looking for answers but it might help others. Here is my code with just for loop and java's substring method...
不太确定 OP 是否仍在寻找答案,但它可能会帮助其他人。这是我的代码,只有 for 循环和 java 的 substring 方法......
public static void main(String ar[])
{
String str = "This is some string. replace lower case is with IS";
String pattern = "is";
String replaceWith = "IS"; // word to replace with
System.out.println(replaceString(str, pattern, replaceWith));
}
static String replaceString(String str, String pattern, String replaceWith) {
String temp = "";
String replacedString = ""; // Replaced String
int remainingString = 0; // append the rest of the string after last
// occurance of pattern.
for (int i = 0; i <= str.length() - pattern.length(); i++) {
temp = str.substring(i, i + 1);
if (str.substring(i, i + pattern.length()).equals(pattern)) {
temp = replaceWith + " ";
i += pattern.length();
}
remainingString = i;
replacedString += temp;
}
replacedString += str.substring(remainingString + 1, str.length());
return replacedString;
}
}