从字符串中删除某些字符 [英] Removing certain characters from a string

查看:114
本文介绍了从字符串中删除某些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用 String.replaceAll()删除字符串中的某些字符。目前还不清楚哪些字符会被删除(即我要删除哪些字符),但我认为任何字符都有效(如 [a-zA-Z] 等等 $%!等等。)

I am thinking about using String.replaceAll() to remove certain characters in my string. It is unclear which characters are going to be removed (i.e. which characters I want to remove), but I would assume that any character is valid (like [a-zA-Z] and things like $%!, etc).

我遇到了http://www.java-tips.org/java-se- tips / java.lang / strip-certain-characters-from-a-string.html 但肯定有一种比迭代每个字符更好的方法......

I came across http://www.java-tips.org/java-se-tips/java.lang/strip-certain-characters-from-a-string.html but surely there is a better way than iterating over each character...

对此有何想法?

谢谢

示例:

为了澄清,我将有不同长度的字符串。我想从中删除字符,确切的在运行时确定,然后返回结果字符串。

Just to clarify, I will have strings of varying lengths. I want to strip characters from it, the exact ones to be determined at runtime, and return the resulting string.

采用上面的段落并允许我删除 ,。,我会返回字符串:

Taking the paragraph above and allowing me to strip out the ",.", I would return the string:


只是为了澄清我的意愿有
不同长度的字符串我想从中删除
字符确切的那些字符到
在运行时确定并返回
结果字符串

Just to clarify I will have strings of varying lengths I want to strip characters from it the exact ones to be determined at runtime and return the resulting string

顺便说一句,我知道replaceAll()使用正则表达式,所以如果我想删除字符$,。,我也需要逃避它们,对吗?

As an aside, I know that replaceAll() uses regular expressions, so if I wanted to strip out the characters "$,.", I would need to escape them too, right?

推荐答案

我想,以下代码可以帮到你。

I guess, the below code will help you.

    String input = "Just to clarify, I will have strings of varying "
      + "lengths. I want to strip characters from it, the exact "
      + "ones to be determined at runtime, and return the "
      + "resulting string.";
    String regx = ",.";
    char[] ca = regx.toCharArray();
    for (char c : ca) {
        input = input.replace(""+c, "");
    }
    System.out.println(input);

这篇关于从字符串中删除某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆