Java 从字符串中删除所有空格和标点符号(不是字母的任何东西)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21946042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove all spaces and punctuation (anything not a letter) from a string?
提问by dagav
In Java, how can I take a string as a parameter, and then remove all punctuation and spaces and then convert the rest of the letters to uppercase?
在Java中,如何将字符串作为参数,然后删除所有标点符号和空格,然后将其余字母转换为大写?
Example 1:
示例 1:
Input: How's your day going?
输入: How's your day going?
Output: HOWSYOURDAYGOING
输出: HOWSYOURDAYGOING
Example 2:
示例 2:
Input: What's your name again?
输入: What's your name again?
Output: WHATSYOURNAMEAGAIN
输出: WHATSYOURNAMEAGAIN
回答by ltalhouarne
String yourString = "How's your day going";
yourString=yourString.replaceAll("\s+",""); //remove white space
yourString=yourString.replaceAll("[^a-zA-Z ]", ""); //removes all punctuation
yourString=yourString.toUpperCase(); //convert to Upper case
回答by C.B.
This should do the trick
这应该可以解决问题
String mystr= "How's your day going?";
mystr = mystr.replaceAll("[^A-Za-z]+", "").toUpperCase();
System.out.println(mystr);
Output:
输出:
HOWSYOURDAYGOING
The regex [^A-Za-z]+
means one or more characters that do not match anything in the range A-Za-z
, and we replace them with the empty string.
正则表达式[^A-Za-z]+
表示一个或多个与 range 中的任何内容都不匹配的字符,A-Za-z
我们将它们替换为空字符串。
回答by Tolis Stefanidis
Well, I did it the long way, take a look if you want. I used the ACII code values (this is my main method, transform it to a function on your own).
好吧,我做了很长的路要走,如果你想看看。我使用了 ACII 代码值(这是我的主要方法,请自行将其转换为函数)。
String str="How's your day going?";
char c=0;
for(int i=0;i<str.length();i++){
c=str.charAt(i);
if(c<65||(c>90&&c<97)||(c>122)){
str=str.replace(str.substring(i,i+1) , "");
}
}
str=str.toUpperCase();
System.out.println(str);
回答by Siddharth Choudhary
I did it with
我做到了
inputText = inputText.replaceAll("\s|[^a-zA-Z0-9]","");
inputText.toUpper(); //and later uppercase the complete string
Though @italhourne 's answer is correct but you can just reduce it in single step by just removing the spaces as well as keeping all the characters from a-zA-Z and 0-9, in a single statement by adding "or". Just a help for those who need it!!
虽然@italhourne 的答案是正确的,但您可以通过添加“或”在单个语句中通过删除空格以及保留 a-zA-Z 和 0-9 中的所有字符来一步减少它。只为有需要的人提供帮助!!
回答by Hemanth Chowdary
public static String repl1(String n){
n = n.replaceAll("\p{Punct}|\s","");
return n;
}