简体   繁体   English

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

[英]How to ignore special characters and spaces in string?

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

   }


   }}

To ignore spaces you can use the following: 要忽略空格,可以使用以下命令:

String.trim();

This will trim all of the blank spaces from the String. 这将trim字符串中的所有空格。 See String.trim() for more information!. 有关更多信息,请参见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]+");
}
  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 = "";
 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. 通过在交换机的情况下使用default,您可以忽略所有其他响应。因此,如果y键入交换机中未包含的任何内容,则不会添加到您的计数或数字中。

You can replace your characters from your string which are non-alphanumeric with blank( "" ) and then do your processing using that string. 您可以将非字母数字字符串中的字符替换为blank( "" ),然后使用该字符串进行处理。 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的答案

If you are trying to simulate a numeric keypad, then you should probably use the blank space and append your string with 0 . 如果要模拟数字小键盘,则可能应该使用blank space并将字符串附加0

Most of the mobile phones have blank space on the number 0 key. 大多数手机的数字0键上都有blank space

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

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. 您可以使用String 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());

You can just add an additional case statement to check for the characters you want to avoid. 您可以仅添加一条额外的case语句来检查要避免的字符。 Then, "do nothing" when this is hit... 然后,当此操作被击中时,“什么也不做”

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM