从字符串中删除所有出现的 char

发布于 2024-10-10 13:59:22 字数 308 浏览 0 评论 0原文

我可以使用这个:

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

Is there a way to remove all栖身的字符X from a String in Java?

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

I can use this:

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

Is there a way to remove all occurrences of character X from a String in Java?

I tried this and is not what I want: str.replace('X',' '); //replace with space

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

放肆 2024-10-17 13:59:22

尝试使用 采用 CharSequence 参数(例如 String)而不是 char 的重载:

str = str.replace("X", "");

Try using the overload that takes CharSequence arguments (eg, String) rather than char:

str = str.replace("X", "");
ゃ人海孤独症 2024-10-17 13:59:22

使用

public String replaceAll(String regex, String replacement)

就会起作用。

用法为str.replace("X", "");

执行

"Xlakjsdf Xxx".replaceAll("X", "");

返回:

lakjsdf xx

Using

public String replaceAll(String regex, String replacement)

will work.

Usage would be str.replace("X", "");.

Executing

"Xlakjsdf Xxx".replaceAll("X", "");

returns:

lakjsdf xx
别理我 2024-10-17 13:59:22

如果您想使用 Java 字符串执行某些操作,Commons Lang StringUtils 是一个值得一看的好地方。

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

If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.

StringUtils.remove("TextX Xto modifyX", 'X');
朦胧时间 2024-10-17 13:59:22
String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";

for(String t : arr)
    ans+=t;

这是我从字符串中删除字符 - 的示例。

String test = "09-09-2012";
String arr [] = test.split("-");
String ans = "";

for(String t : arr)
    ans+=t;

This is the example for where I have removed the character - from the String.

风筝有风,海豚有海 2024-10-17 13:59:22

你好试试下面的代码

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();
    }
}

Hello Try this code below

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();
    }
}
眼泪都笑了 2024-10-17 13:59:22

使用性能基准评估主要答案,这证实了当前选择的答案在幕后进行了昂贵的正则表达式操作的担忧

迄今为止,提供的答案有 3 种主要风格(忽略JavaScript 答案 ;) ):

  • 使用 String.replace(charsToDelete, "");它在底层使用正则表达式
  • 使用 Lambda
  • 使用简单的 Java 实现

就代码大小而言,显然 String.replace 是最简洁的。简单的 Java 实现比 Lambda 更小、更干净(恕我直言)(不要误会我的意思 - 我经常在合适的地方使用 Lambda)

执行速度是,按照最快到最慢的顺序:简单的 Java 实现、Lambda,然后String.replace()(调用正则表达式)。

到目前为止,最快的实现是简单的 Java 实现,经过调整,它将 StringBuilder 缓冲区预分配到最大可能的结果长度,然后简单地将不在“要删除的字符”字符串中的字符附加到缓冲区。这避免了对于 Strings > 可能发生的任何重新分配。长度为 16 个字符(StringBuilder 的默认分配),它避免了 Lambda 实现中发生的从字符串副本中删除字符的“向左滑动”性能影响。

下面的代码运行一个简单的基准测试,运行每个实现 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 实现本身可能会产生一些开销。

String.replace 实现使用正则表达式并在每次调用时执行正则表达式“编译”。对此的优化是直接使用正则表达式并缓存已编译的模式,以避免每次编译的成本。

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));
    }
}

Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood

To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):

  • Use String.replace(charsToDelete, ""); which uses regex under the hood
  • Use Lambda
  • Use simple Java implementation

In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)

Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes 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.

The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.

The exact results vary with each run but the order of performance never changes:

Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms

The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.

The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.

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));
    }
}
断舍离 2024-10-17 13:59:22

替换时需要将需要删除的字符放在方括号内。示例代码如下:

String s = "$116.42".replaceAll("[$]", "");

You will need to put the characters needs to be removed inside the square brackets during the time of replacement. The example code will be as following:

String s = "$116.42".replaceAll("[$]", "");
木格 2024-10-17 13:59:22

我喜欢在这种情况下使用正则表达式:

str = str.replace(/X/g, '');

其中 g 表示全局,因此它将遍历整个字符串并将所有 X 替换为 '';
如果你想同时替换 X 和 x,你只需说:(

str = str.replace(/X|x/g, '');

请参阅我的小提琴:fiddle)

I like using RegEx in this occasion:

str = str.replace(/X/g, '');

where g means global so it will go through your whole string and replace all X with '';
if you want to replace both X and x, you simply say:

str = str.replace(/X|x/g, '');

(see my fiddle here: fiddle)

盛夏已如深秋| 2024-10-17 13:59:22

使用replaceAll 而不是replace

str = str.replaceAll("X,"");

这应该会给你想要的答案。

Use replaceAll instead of replace

str = str.replaceAll("X,"");

This should give you the desired answer.

秋千易 2024-10-17 13:59:22

这里是一个 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 XYtomodifyZ";
deleteChars.apply(str, "XYZ"); // –> “要修改的文本”

该解决方案考虑到,与 replace() 不同的是,在删除字符时,结果字符串永远不会变得大于起始字符串。因此,它避免了像 replace() 那样按字符附加到 StringBuilder 时的重复分配和复制。
更不用说在 replace() 中毫无意义地生成 PatternMatcher 实例,而这些实例永远不需要删除。
replace() 不同的是,该解决方案可以一次性删除多个字符。

here is a lambda function which removes all characters passed as string

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"

This solution takes into acount that the resulting String – in difference to replace() – never becomes larger than the starting String when removing characters. So it avoids the repeated allocating and copying while appending character-wise to the StringBuilder as replace() does.
Not to mention the pointless generation of Pattern and Matcher instances in replace() that are never needed for removal.
In difference to replace() this solution can delete several characters in one swoop.

神回复 2024-10-17 13:59:22

...另一个 lambda
从原始字符串复制一个新字符串,但省略要删除的字符

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 );

给出:从字符串中移动特殊字符

…another lambda
copying a new string from the original, but leaving out the character that is to delete

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 );

gives: rmoving a spcial charactr from a string

暮色兮凉城 2024-10-17 13:59:22
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);
        }
    }
}
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);
        }
    }
}
一抹微笑 2024-10-17 13:59:22

您可以使用 str = str.replace("X", ""); 如前所述,您会没事的。供您参考,'' 不是空(或有效)字符,但 '\0' 是。

因此,您可以使用 str = str.replace('X', '\0'); 代替。

You can use str = str.replace("X", ""); as mentioned before and you will be fine. For your information '' is not an empty (or a valid) character but '\0' is.

So you could use str = str.replace('X', '\0'); instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文