java 如何忽略字符串中的特殊字符和空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31716511/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:02:09  来源:igfitidea点击:

How to ignore special characters and spaces in string?

javaregex

提问by toobadgoo

So i developed this code to convert a word to phone numbers and how do i code it to ignore the spaces entered while displaying the result?

所以我开发了这个代码来将一个单词转换为电话号码,我如何编码它以忽略在显示结果时输入的空格?

So what i meant is to allow the user to entered spaces between the words but is not reflected in the result.

所以我的意思是允许用户在单词之间输入空格,但不会反映在结果中。

 import java.util.Scanner;

{
public static void main (String[] args)
{
Scanner  console = new Scanner(System.in);


{  
System.out.println("Enter the a word to be converted : ");

String  Letter = console.next ();
Letter = Letter.toUpperCase();
Letter = Letter.toLowerCase();
String  Number="";

int count=0;
int  i=0;

while(count < Letter.length())
  {switch(Letter.charAt(i))
   {case 'A':case 'B':case 'C': case 'a': case 'b': case 'c':
              Number += "2";
              count++;
      break;
  case 'D':case 'E':case 'F': case 'd': case 'e': case 'f':
               Number += "3";
              count++;
      break;
   case 'G':case 'H':case 'I': case 'g': case 'h': case 'i':
              Number += "4";
              count++;
      break;
    case 'J':case 'K':case 'L': case 'j': case 'k': case 'l':

              Number += "5";
             count++;
      break;
    case 'M':case 'N':case 'O': case 'm': case 'n': case 'o':
          Number += "6";
              count++;
      break; 
    case 'P':case 'R':case 'S': case 'p': case 'r': case 's':
              Number += "7";
              count++;
      break;
    case 'T':case 'U':case 'V': case 't': case 'u': case 'v': 
            Number += "8";   
            count++;
      break;
    case 'W':case 'X':case 'Y':case 'Z': case 'w': case 'x': case 'y': case 'z':
         Number += "9";
         count++;
      break;
      }
    if(  count==3) {
       Number += "-";
   }
   i++;
           }     
    System.out.println( Number );

   }


   }}

回答by James

To ignore spaces you can use the following:

要忽略空格,您可以使用以下命令:

String.trim();

This will trimall of the blank spaces from the String. See String.trim()for more information!.

这将trim是字符串中的所有空格。有关更多信息,请参见String.trim()

And to check whether the String contains anything besides letters you can use:

并检查字符串是否包含除字母之外的任何内容,您可以使用:

public boolean isAlpha(String name) {
    char[] chars = name.toCharArray();

    for (char c : chars) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }

    return true;
}

If you want speed, or for simplicity, you can use:

如果你想要速度,或者为了简单起见,你可以使用:

public boolean isAlpha(String name) {
    return name.matches("[a-zA-Z]+");
}

回答by rhitz

  String content = "asda saf oiadgod iodboiosb dsoibnos";
  content = content.replaceAll("\s", "");
  System.out.println(content);

For your code

对于您的代码

System.out.println("Enter the a word to be converted : ");

    String Letter = console.nextLine();
    Letter = Letter.replaceAll("\s", "");
    Letter = Letter.toUpperCase();
    Letter = Letter.toLowerCase();
    String Number = "";

回答by Shrinivas Shukla

If you are trying to simulate a numeric keypad, then you should probably use the blank spaceand append your string with 0.

如果您正在尝试模拟数字小键盘,那么您可能应该使用blank space并在您的字符串后附加0.

Most of the mobile phones have blank spaceon the number 0key.

大多数手机上都有blank space数字0键。

case ' ':
    Number += "0";
    count++;
    break;

回答by Loganathan Mohanraj

The following piece of code might help you. I just optimized your code above. You can replace the characters with numbers using the String APIs instead of iterating the string character by character and generating the number.

以下代码可能对您有所帮助。我刚刚优化了你上面的代码。您可以使用字符串 API 将字符替换为数字,而不是逐个字符地迭代字符串并生成数字。

Scanner console = new Scanner(System.in);    
String str = console.next();

// To trim the leading and trailing white spaces
str = str.trim();

// To remove the white spaces in between the string
while (str.contains(" ")) {
    str = str.replaceAll(" ", "");
}

// To replace the letters with numbers
str = str.replaceAll("[a-cA-C]", "2").replaceAll("[d-fD-F]", "3")
    .replaceAll("[g-iG-I]", "4").replaceAll("[j-lJ-L]", "5")
    .replaceAll("[m-oM-O]", "6").replaceAll("[p-sP-S]", "7")
    .replaceAll("[t-vT-V]", "8").replaceAll("[w-zW-Z]", "9");

System.out.println(str);

If you want to insert an "-" after 3 digits, you can use the following piece code after the above conversion.

如果你想在3位后插入一个“-”,你可以使用上面转换后的以下片段代码。

StringBuffer buff = new StringBuffer(str);
buff.insert(3, "-");

System.out.println(buff.toString());

回答by Keshav Pandey

 import java.util.Scanner;

{
public static void main (String[] args)
{
Scanner  console = new Scanner(System.in);


{  
System.out.println("Enter the a word to be converted : ");

String  Letter = console.next ();
Letter = Letter.toUpperCase();
Letter = Letter.toLowerCase();
String  Number="";

int count=0;
int  i=0;

while(count < Letter.length())
  {switch(Letter.charAt(i))
   {
   case 'A':case 'B':case 'C': case 'a': case 'b': case 'c':
              Number += "2";
              count++;
      break;
  case 'D':case 'E':case 'F': case 'd': case 'e': case 'f':
               Number += "3";
              count++;
      break;
   case 'G':case 'H':case 'I': case 'g': case 'h': case 'i':
              Number += "4";
              count++;
      break;
    case 'J':case 'K':case 'L': case 'j': case 'k': case 'l':

              Number += "5";
             count++;
      break;
    case 'M':case 'N':case 'O': case 'm': case 'n': case 'o':
          Number += "6";
              count++;
      break; 
    case 'P':case 'R':case 'S': case 'p': case 'r': case 's':
              Number += "7";
              count++;
      break;
    case 'T':case 'U':case 'V': case 't': case 'u': case 'v': 
            Number += "8";   
            count++;
      break;
    case 'W':case 'X':case 'Y':case 'Z': case 'w': case 'x': case 'y': case 'z':
         Number += "9";
         count++;
      break;
    default:
        //Ignore anything else
        break;
      }
    if(  count==3) {
       Number += "-";
   }
   i++;
           }     
    System.out.println( Number );

   }


   }}

By using default in your switch case you can ignore all other responses.So if the y type anything which is not included in your switch it won't add to your count or number.

通过在您的 switch 案例中使用默认值,您可以忽略所有其他响应。因此,如果 y 键入任何未包含在您的 switch 中的内容,它不会添加到您的计数或数字中。

回答by Naman Gala

You can replace your characters from your string which are non-alphanumeric with blank("") and then do your processing using that string. You can use String.replaceAll()method.

您可以将字符串中的非字母数字字符替换为空白(""),然后使用该字符串进行处理。您可以使用String.replaceAll()方法。

Replaces each substring of this string that matches the given regular expression with the given replacement.

用给定的替换替换此字符串中与给定正则表达式匹配的每个子字符串。

For Eg:

对于例如:

String str = "abc..,df.,";
String alphaNumericStr = str.replaceAll("[^a-zA-Z0-9]", "");
System.out.println(alphaNumericStr); // Prints > abcdf

while(count < alphaNumericStr.length()) { // using alphaNumericStr instead of Letter
    ...


Another approach(I would prefer this): Refer answer by @KeshavPandey

另一种方法(我更喜欢这个):参考@KeshavPandey 的回答

回答by juansta

You can just add an additional case statement to check for the characters you want to avoid. Then, "do nothing" when this is hit...

您可以添加一个额外的 case 语句来检查您想要避免的字符。然后,当它被击中时“什么都不做”......

In your case of just wanting to skip spaces, you could add an additional case specific to the ' ' character, and/or a default case;

在您只想跳过空格的情况下,您可以添加特定于 ' ' 字符的附加案例和/或默认案例;

case ' ':
default:
    break;