1

I'm able to separate the words in the sentence but I do not know how to check if a word contains a character other than a letter. You don't have to post an answer just some material I could read to help me.

public static void main(String args [])
{
    String sentance;
    String word;
    int index = 1;

    System.out.println("Enter sentance please");
    sentance = EasyIn.getString();

    String[] words = sentance.split(" ");    

    for ( String ss : words ) 
    {
        System.out.println("Word " + index + " is " + ss);
        index++;
    }            
}   
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Wookie Commander
  • 13
  • 1
  • 1
  • 5

5 Answers5

5

What I would do is use String#matches and use the regex [a-zA-Z]+.

String hello = "Hello!";
String hello1 = "Hello";

System.out.println(hello.matches("[a-zA-Z]+"));  // false
System.out.println(hello1.matches("[a-zA-Z]+")); // true

Another solution is if (Character.isLetter(str.charAt(i)) inside a loop.


Another solution is something like this

String set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String word = "Hello!";

boolean notLetterFound;
for (char c : word.toCharArray()){  // loop through string as character array
    if (!set.contains(c)){         // if a character is not found in the set
        notLetterfound = true;    // make notLetterFound true and break the loop
        break;                       
    }
}

if (notLetterFound){    // notLetterFound is true, do something
    // do something
}

I prefer the first answer though, using String#matches

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • See the thing is I need to check all of the words individually and see if they have a character other than a letter and the output whether its a good word(contains only letters) or a bad word (for example "Hell0" is a bad word) – Wookie Commander Dec 13 '13 at 15:44
  • In your loop, just use `if (ss.matches("[a-zA-Z]+")) { // do something }`. – Paul Samsotha Dec 13 '13 at 15:48
1

For more reference goto-> How to determine if a String has non-alphanumeric characters?
Make the following changes in pattern "[^a-zA-Z^]"

Community
  • 1
  • 1
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
0

Not sure if I understand your question, but there is the

Character.isAlpha(c);

You would iterate over all characters in your string and check whether they are alphabetic (there are other "isXxxxx" methods in the Character class).

geert3
  • 7,086
  • 1
  • 33
  • 49
0

You could loop through the characters in the word calling Character.isLetter(), or maybe check if it matches a regular expression e.g. [\w]* (this would match the word only if its contents are all characters).

stripybadger
  • 4,539
  • 3
  • 19
  • 26
-1

you can use charector array to do this like..

char[] a=ss.toCharArray();

not you can get the charector at the perticulor index.

with "word "+index+" is "+a[index];

deepak tiwari
  • 107
  • 10