Question:
Check if String contains only letters?
1970-01-01 00:00:00 UTC
Check if String contains only letters?
Three answers:
2016-02-27 11:02:45 UTC
Or u can try regular expression with \d+ as matching pattern.
pullmyefinger
2011-02-24 04:45:12 UTC
I don't know Java or C, but what I would do is logically as follows:



Remember or Learn ASCII Character Codes for A-Z (ASCII 65-90) or a-z (ASCII 97-122) //www.asciitable.com or do google on ascii table



Notice that there is a Difference of exactly 32 between the uppercase A and the lowercase a, and this pattern follows for the remainder of the alphabet. JAVA should have an "ASC" function that will give you the ascii value of each character you choose (in a loop from the first character to the last character)... Capiche??



Logic:



1- ask for a string of characters to be entered from the keyboard and stored in some character/text variable.



2- use a Java function like "LEN" that will give you the LENgth (number of characters in the string)

that is stored in the variable in (1). Store that INTEGER number in a different variable. THIS Variable tells you the end value of your processing loop.



3- You could also do error checking (and you should) to make sure that the user did not just press Enter. (Hint: If they did press enter, the LENgth of the string would be ZERO). Use an IF to check.



4- If the LENgth of the string is > 0, run a loop that runs from 1 to the number of characters in the string. (the variable you created in (2) ). This again is your processing loop.



Now, there are two ways to do this.



All you have right now is a character/text variable that contains a string (such as StringA) and a numeric variable (numcharsA) that contains a number referring to the length of stringA.



What you do now is to create two arrays that are the size/number of elements in the variable numcharsA.



Then:



Create a first processing loop that reads each character from the variable StringA into the first array you created. To do this you will need a Java function that can isolate individual characters in a string and store them to a variable like currentchar(acter).



Once you have the current character from StringA isolated, you can CHECK The ASCII Value of that character to see if it is either an upper or lower case letter of the alphabet:



IF the ASCII value of the isolated character (stored in the variable currentchar) is between 65 and 97 (>64 AND <91) (A-Z) OR (>96 and <123) (a-z) THEN



Put that character in the SECOND Array you created. This second array is only to store the valid letters of the alphabet.



When your loop is done, This Array will have the original inputted string WITHOUT Non-Alphabetic Characters (nothing but A-Z or a-z). The reason this works is the ASC function above is your check to see if the current character is Alphabetic. THIS IS WHAT Character.isLetter actually does, and is another way of going about it.



There normally is always more than one way to do something in any programming language.





This may sound like alot of reading, but make sure you understand the logical steps I wrote. MOST Beginning programmers want to just get an Incomplet Idea of how to do something and start writing Code. 99% of the time That Approach does not work, and the bad part of it is that since you don't know the correct logical flow (possibly) you don't know where to start to look for errors when the program doesn't work.



It IS more work, it DOES suck to have to do it but once you get used to that method your programs will take ALOT LESS TIME to write. Ask your instructor for the logical steps to be explained again and write them down. If they don't/won't give them to you then you need a new Instructor, but that is probably not the case.



You can't even write software "to scratch your butt" correctly without a Flowchart/Logical set of steps...



Good luck, this program will not take many steps at all vs. the paragraphs that i wrote.
es
2011-02-24 00:42:06 UTC
EDIT:



I finally hacked together a working but very inelegant implementation of your algorithm to remove all non-letter chars (if you wanted to include spaces in the result, you could add in an "or" clause using Character.isSpaceChar or Character.isWhitespace ) I wrote it using an instance var, but you could just as easily make it static, public static String removeNonLetters( String inputString ) { (...) }



public String removeNonLetters( ) {

//   returns copy of instance var inputString with only letters



  String result = new String( );

  for( int i=0; i < inputString.length( ); i++ ) {

    if( Character.isLetter( inputString.charAt( i ) ) )

      result += inputString.charAt( i );

  }

  return result;

}



StringTokenizer() seems to me like a great method to use (especially if you can give it a list of which chars to consider delimiters, as you can in C's version of it), although the API ( http://download.oracle.com/javase/6/docs/api/index.html ) has deprecated it and says to use the split method of String or the java.util.regex package instead.



From the sample use of split() in the API (in, oddly enough, the page for StringTokenizer, not for String), it looks as if you can designate your delimiter chars,



String[] result = "this is a test".split("\\s");

  for (int x=0; x
   System.out.println(result[x]);



A couple of brief examples are on the String page of the API (find String[] split(String regex) in the method summary and click on it at http://download.oracle.com/javase/6/docs/api/java/lang/String.html )



"Splits this string around matches of the given regular expression (...)



The string "boo:and:foo", for example, yields the following results with these expressions:



Regex Result

======= ==========

: { "boo", "and", "foo" }

o { "b", "", ":and:f" }



Your ideas seem fine to me, as much of it as you were able to type in (yahoo length limits?)



EDIT: The below did not work as I expected



You could use Java String's matches( regexp ) to match to letters. If Java follows the same conventions as UNIX it would be



if (!testString.matches( "[a-zA-Z]*" ) ) {

  /* remove non-letters */

  testString.replaceAll( "^[a-zA-Z]", "" );

}



in regular expressions, [] signifies a group of characters,

  [a-zA-Z] designates anything in the range a-z or the range A-Z

  Putting a * after it matches 0 or more of these things, so [a-zA-Z]* matches 0 or more occurrences of lower case or upper case letters

  ^ is used for "not" so ^[a-zA-Z] designates any character not in the designated group (here, any non-alphabetic character)

  String's replaceAll method replaces each substring that matches the regular expression in the first argument, with the given replacement (in this case, blank)



EDIT: I can't get it to work. I'll try another approach


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...