Java 从字符串中删除所有出现的字符
我可以用这个:Java 从字符串中删除所有出现的字符,java,string,character,Java,String,Character,我可以用这个: String str = "TextX Xto modifyX"; str = str.replace('X','');//that does not work because there is no such character '' 有没有一种方法可以从Java中的字符串中删除所有出现的字符X 我试过了,但不是我想要的:str.replace('X','')//使用空格替换为空格 public String replaceAll(String regex, String r
String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''
有没有一种方法可以从Java中的字符串中删除所有出现的字符X
我试过了,但不是我想要的:str.replace('X','')//使用空格替换为空格
public String replaceAll(String regex, String replacement)
会有用的
用法将是str.replace(“X”,“X”)代码>
执行
"Xlakjsdf Xxx".replaceAll("X", "");
返回:
lakjsdf xx
尝试使用(例如,String
)而不是char
:
str = str.replace("X", "");
如果你想用Java字符串做一些事情,这是一个很好的地方
StringUtils.remove("TextX Xto modifyX", 'X');
您可以使用str=str.replace(“X”,“X”)代码>如前所述,您会没事的。请注意,“
不是空字符(或有效字符),但”\0“
是空字符
因此可以使用str=str.replace('X','\0')代码>取而代之
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();
}
}
公共类RemoveCharacter{
公共静态void main(字符串[]args){
String str=“MXy nameX iXs farXazX”;
char x='x';
系统输出println(removeChr(str,x));
}
公共静态字符串removeChr(字符串str,char x){
StringBuilder strBuilder=新StringBuilder();
char[]rmString=str.toCharArray();
对于(int i=0;i我喜欢在这种情况下使用正则表达式:
str = str.replace(/X/g, '');
其中g表示全局,因此它将遍历整个字符串,并将所有X替换为“”;
如果要同时替换X和X,只需说:
str = str.replace(/X|x/g, '');
(见我的小提琴:)package com.acn.demo.action;
公共类RemoveCharFromString{
静态字符串输入=”;
公共静态void main(字符串[]args){
input=“abadbb34erterb”;
字符标记='b';
removeChar(代币);
}
私有静态void removeChar(字符令牌){
//TODO自动生成的方法存根
系统输出打印项次(输入);
对于(int i=0;i使用replaceAll而不是replace
str = str.replaceAll("X,"");
这将为您提供所需的答案。这里有一个lambda函数,用于删除作为字符串传递的所有字符
BiFunction deleteChars=(fromString,chars)->{
StringBuilder buf=新的StringBuilder(fromString);
IntStream.range(0,buf.length()).forEach(i->{
而(i=0)
buf.deleteCharAt(i);
} );
返回(buf.toString());
};
String str=“textxyto modifyZ”
deleteChars.apply(str,“XYZ”);/–>“要修改的文本”
此解决方案考虑到结果字符串(与replace()
不同)在删除字符时不会大于起始字符串。因此,它避免了在向StringBuilder
添加字符时重复分配和复制,就像replace()
那样。
更不用说在replace()
中毫无意义地生成了模式
和匹配器
实例,这些实例永远不需要删除。
与replace()
不同的是,此解决方案可以一次删除多个字符。使用性能基准评估主要答案,以确认当前选择的答案会导致昂贵的正则表达式操作
迄今为止,提供的答案有3种主要样式(忽略JavaScript答案;):
- 使用String.replace(charsToDelete,“”);它在引擎盖下使用正则表达式
- 使用Lambda
- 使用简单的Java实现
就代码大小而言,String.replace显然是最简洁的。简单的Java实现比Lambda稍微小一些,更干净(IMHO)(别误会,我经常在合适的地方使用Lambda)
执行速度从快到慢依次为:简单Java实现、Lambda和String.replace()(调用regex)
到目前为止,最快的实现是经过调优的简单Java实现,它将StringBuilder缓冲区预先分配到可能的最大结果长度,然后简单地将不在“chars to delete”字符串中的字符追加到缓冲区。这避免了长度大于16个字符的字符串可能发生的任何重新分配(StringBuilder的默认分配),它避免了Lambda实现中从字符串副本中删除字符的“向左滑动”性能影响
下面的代码运行一个简单的基准测试,每个实现运行1000000次,并记录运行时间
每次运行的确切结果各不相同,但性能顺序从未改变:
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
Lambda实现(从Kaplan的答案中复制)可能会较慢,因为它会将所有字符“左移一”到被删除字符的右侧。对于需要删除大量字符的较长字符串,这显然会变得更糟。Lambda实现本身也可能有一些开销
String.replace实现使用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));
}
}
package.com.sample;
导入java.util.function.BiFunction;
导入java.util.stream.IntStream;
公共班机{
静态公共字符串deleteCharsSimple(String fromString,String charsToDelete)
{
StringBuilder buf=新的StringBuilder(fromString.length());//预先分配到最大可能结果长度
for(int i=0;i{
StringBuilder buf=n
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));
}
}
String s = "$116.42".replaceAll("[$]", "");
String text = "removing a special character from a string";
int delete = 'e';
int[] arr = text.codePoints().filter( c -> c != delete ).toArray();
String rslt = new String( arr, 0, arr.length );