我可以使用这个:
String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''
有没有一种方法可以从Java中删除所有出现的字符X
?
我尝试了这个,但这不是我想要的:str.replace('X',' '); //用空格替换
X
是 char 类型,该怎么办? - KNUstr = str.replace("\uffff", "");
- Jaime Hablutzel使用
public String replaceAll(String regex, String replacement)
这将有效。
使用方法如下:str.replace("X", "");
。
执行:
"Xlakjsdf Xxx".replaceAll("X", "");
返回:
lakjsdf xx
CharSequence
的replace
重载方法。 - LukeHStringUtils.remove("TextX Xto modifyX", 'X');
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";
for(String t : arr)
ans+=t;
这是一个示例,我已将字符串中的“-”字符删除。
你好,请尝试下面的代码:
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();
}
}
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
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));
}
}
使用replaceAll替代replace
str = str.replaceAll("X,"");
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
- Molasses在这种情况下,我喜欢使用正则表达式:
str = str.replace(/X/g, '');
这里的g代表全局,所以它将遍历整个字符串并将所有的X替换为''; 如果你想同时替换X和x,只需输入:
str = str.replace(/X|x/g, '');
在替换时,您需要将需要删除的字符放在方括号内。示例代码如下:
String s = "$116.42".replaceAll("[$]", "");
这是一个 Lambda 函数,它可以删除传递的所有字符。
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() );
};
String str = "TextX XYto modifyZ";
deleteChars.apply( str, "XYZ" ); // –> "Text to modify"
这个解决方案考虑到了在删除字符时,结果字符串永远不会比起始字符串更大,因此避免了像replace()
一样重复分配和复制,而是逐个字符地附加到StringBuilder
中。
更不用说在replace()
中无意义地生成Pattern
和Matcher
实例,这些实例在删除时从未被使用。
与replace()
不同,这个解决方案可以一次性删除多个字符。
str.replace("…", "")
实例化了 private Pattern(…)
,然后在生成的模式上调用 public String replaceAll(String repl)
。因此,以下函数调用发生了:return Pattern.compile(target.toString(), Pattern.LITERAL).matcher( this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
- 请参见 Sal_Vader_808 的评论。总体而言,这比我 hip lambda 解决方案多大约三倍。这里很好地解释了为什么我的 hip lambda 解决方案也更快:为什么Java的String::replace()如此缓慢? - Kaplan