我可以用这个:
String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''
是否有一种方法来删除字符X的所有出现从一个字符串在Java?
我尝试了这个,不是我想要的:str.replace('X',' ');//替换为空格
我可以用这个:
String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''
是否有一种方法来删除字符X的所有出现从一个字符串在Java?
我尝试了这个,不是我想要的:str.replace('X',' ');//替换为空格
当前回答
你好试试下面的代码
public class RemoveCharacter {
public static void main(String[] args){
String str = "MXy nameX iXs farXazX";
char x = 'X';
System.out.println(removeChr(str,x));
}
public static String removeChr(String str, char x){
StringBuilder strBuilder = new StringBuilder();
char[] rmString = str.toCharArray();
for(int i=0; i<rmString.length; i++){
if(rmString[i] == x){
} else {
strBuilder.append(rmString[i]);
}
}
return strBuilder.toString();
}
}
其他回答
如果你想用Java字符串做一些事情,Commons Lang StringUtils是一个很好的地方。
StringUtils.remove("TextX Xto modifyX", 'X');
尝试使用重载来接受CharSequence参数(例如,String)而不是char:
str = str.replace("X", "");
用性能基准评估主要答案,确认当前选择的答案在底层进行了代价高昂的正则表达式操作
到目前为止,提供的答案有3种主要风格(忽略JavaScript的答案;)):
使用字符串。替换(charsToDelete”、“);哪个在引擎盖下使用正则表达式 使用λ 使用简单的Java实现
在代码大小方面,显然是字符串。替换是最简洁的。简单的Java实现比Lambda更小更干净(恕我直言)(不要误解我的意思-我经常在合适的地方使用Lambdas)
执行速度从快到慢依次是:简单的Java实现,Lambda,然后是String.replace()(调用regex)。
By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.
下面的代码运行一个简单的基准测试,每个实现运行1,000,000次,并记录运行时间。
每次运行的准确结果都不同,但性能的顺序永远不变:
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
Lambda实现(从Kaplan的答案中复制)可能更慢,因为它执行所有字符中的“左移一个”到被删除字符的右侧。对于需要删除大量字符的较长字符串,情况显然会更糟。另外,Lambda实现本身可能会有一些开销。
的字符串。替换实现,使用regex并在每次调用时执行regex“编译”。对此的一种优化方法是直接使用regex并缓存已编译的模式,以避免每次编译的成本。
package com.sample;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
public class Main {
static public String deleteCharsSimple(String fromString, String charsToDelete)
{
StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
for(int i = 0; i < fromString.length(); i++)
if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
buf.append(fromString.charAt(i)); // char not in chars to delete so add it
return buf.toString();
}
static public String deleteCharsLambda(String fromString1, String charsToDelete)
{
BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder(fromString);
IntStream.range(0, buf.length()).forEach(i -> {
while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
buf.deleteCharAt(i);
});
return (buf.toString());
};
return deleteChars.apply(fromString1, charsToDelete);
}
static public String deleteCharsReplace(String fromString, String charsToDelete)
{
return fromString.replace(charsToDelete, "");
}
public static void main(String[] args)
{
String str = "XXXTextX XXto modifyX";
String charsToDelete = "X"; // Should only be one char as per OP's requirement
long start, end;
System.out.println("Start simple");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsSimple(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start lambda");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsLambda(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start replace");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsReplace(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
}
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
for(String t : arr)
ans+=t;
这是我从字符串中删除字符的示例。
使用replaceAll代替replace
str = str.replaceAll("X,"");
这应该会给你想要的答案。