我可以用这个:

String str = "TextX Xto modifyX";
str = str.replace('X','');//that does not work because there is no such character ''

是否有一种方法来删除字符X的所有出现从一个字符串在Java?

我尝试了这个,不是我想要的:str.replace('X',' ');//替换为空格


当前回答

这里是一个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() );
};

字符串 str = “TextX XYto modifyZ”; deleteChars.apply( str, “XYZ” ); –> “要修改的文本”

此解决方案考虑到,在删除字符时,生成的字符串(in difference to replace())永远不会比起始字符串大。因此,它避免了在像replace()那样将字符附加到StringBuilder时重复分配和复制。 更不用说replace()中毫无意义的Pattern和Matcher实例的生成,这些实例永远不需要删除。 在difference to replace()中,此解决方案可以一次性删除多个字符。

其他回答

你可以使用str = str.replace("X", "");如前所述,你会没事的。“”不是空字符(或有效字符),而“\0”是。

所以你可以使用str = str.replace('X', '\0');代替。

如果你想用Java字符串做一些事情,Commons Lang StringUtils是一个很好的地方。

StringUtils.remove("TextX Xto modifyX", 'X');

尝试使用重载来接受CharSequence参数(例如,String)而不是char:

str = str.replace("X", "");
package com.acn.demo.action;

public class RemoveCharFromString {

    static String input = "";
    public static void main(String[] args) {
        input = "abadbbeb34erterb";
        char token = 'b';
        removeChar(token);
    }

    private static void removeChar(char token) {
        // TODO Auto-generated method stub
        System.out.println(input);
        for (int i=0;i<input.length();i++) {
            if (input.charAt(i) == token) {
            input = input.replace(input.charAt(i), ' ');
                System.out.println("MATCH FOUND");
            }
            input = input.replaceAll(" ", "");
            System.out.println(input);
        }
    }
}

用性能基准评估主要答案,确认当前选择的答案在底层进行了代价高昂的正则表达式操作

到目前为止,提供的答案有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));
    }
}