toobadgoo
toobadgoo

Reputation: 13

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

   }


   }}

Upvotes: 0

Views: 28531

Answers (7)

rhitz
rhitz

Reputation: 1892

  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 = "";

Upvotes: 2

Loganathan Mohanraj
Loganathan Mohanraj

Reputation: 1874

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.

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.

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

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

Upvotes: 0

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4453

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

Most of the mobile phones have blank space on the number 0 key.

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

Upvotes: 0

Naman Gala
Naman Gala

Reputation: 4692

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.

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

Upvotes: 0

Keshav Pandey
Keshav Pandey

Reputation: 73

 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.

Upvotes: 0

James
James

Reputation: 469

To ignore spaces you can use the following:

String.trim();

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

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]+");
}

Upvotes: 3

juansta
juansta

Reputation: 1

You can just add an additional case statement to check for the characters you want to avoid. 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;

Upvotes: -1

Related Questions