Jump to content

string contain only (a-z) ,(A-Z)

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
eman ahmed

eman ahmed

    Learning Programmer

  • Members
  • PipPipPip
  • 79 posts
how can I know that the string contian only the alphabatic from (a....z)
and (A....Z) and doesn't contain any symbol like ( ,-'
I want to do that by scan astring from left to right and check each character in it by
if(.........)
now what's the condition I should write it

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
If you're wanting to scan, instead of relying on regex here is a simple option:

private boolean onlyLetters(final String s) {
  final char[] chars = s.toCharArray();
  for (int x = 0; x < chars.length; x++) {      
    final char c = chars[x];
    if ((c >= 'a') && (c <= 'z')) continue; // lowercase
    if ((c >= 'A') && (c <= 'Z')) continue; // uppercase
    return false;
  }  
  return true;
}

If you're wanting to use simple regular expressions:
boolean onlyLetters(String str) {
   return str.matches("^[a-zA-Z]+$");
}

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
I see that you use ^ and $ in the regex. I see that a lot, but what does it do? I think i've read that $ matches a endline or newline char, but the ^?

That was also an issue in this thread: http://forum.codecal...al-c-regex.html

#4
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts

oxano said:

I see that you use ^ and $ in the regex. I see that a lot, but what does it do? I think i've read that $ matches a endline or newline char, but the ^?

^: Field starts with.
$: Field ends with.

If they're not used it will simply match "if it contains [a-zA-Z]" and not "if it only contains [a-zA-Z]"
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#5
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
Oh, okay. I still don't get what was wrong in the c# tut then :s

Edit: oh wait, i do now :D nevermind