I am a beginner learning Java and have been asked to check if a given string is a palindrome.
Here is what I have so far:
int namel = name.length();
for (int i =0; i<=namel; i++)
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
String letterS =txtNamePali.getText();
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
}
Unfortunately my textbox isn't showing any output. I have searched for how to fix the issue but couldn't find an answer relating to what I have learnt in class.
What did I do wrong, and how can I correct it?
I think the easiest test is to use the StringBuilder.reverse() to construct the reverse of the input. Also, the word is usually spelled palindrome.
StringBuilder sb = new StringBuilder(name);
sb.reverse();
String msg = (sb.toString().equals(name)) ? "Palindrome" : "Not a Palindrome";
txtNamePali.setText(msg);
You can do it using a StringBuilder
Use the reverse function in that.
Example:
public static void main(String args[]){
String str = "1234";
String str1 = "1234321";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
if(stringBuilder.reverse().toString().equals(str)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
stringBuilder = new StringBuilder();
stringBuilder.append(str1);
if(stringBuilder.reverse().toString().equals(str1)){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
Output:
Not Palindrome
Palindrome
Int short you can just do
new StringBuilder().append(yourString).reverse().toString().equals(yourString)
This return a boolean true if the string is palindrome else false.
Your code is on the right track, but as some people have said, there are a few errors you need to account for, which should appear as compiler issues.
int namel = name.length();
boolean isPalindrome = true;
//add a tracking value, it's a palindrome unless we prove it otherwise
for (int i =0; i< namel/2; i++)
//change from <= to < because arrays are 0-index, we also only have to check halfway so we can use namel/2
{
char letter = name.charAt(i);
char namerev = name.charAt(namel-i);
//String letterS =txtNamePali.getText(); <-- not sure what this was for, possibly a debug statement
if(letter!=namerev)
{
isPalindrome = false; //we have found a non-matching value, it'll stay false, and we'll output correctly
}
}
//then we set the text once. Keeping the text inside would have returned an erroneous "abbc" is a palindrome.
if(isPalindrome) {
txtNamePali.setText("Palindrone");
}
else {
txtNamePali.setText( "Not a Palindrone");
}
1.The result of the method should be given when the whole string got checked. So first put
if(letter==namerev)
{
txtNamePali.setText("Palindrone");
}
else
{
txtNamePali.setText( "Not a Palindrone");
}
outside the loop (and change the condition - like in my proposal below).
you can break the loop when the first mismatch of two chars occured.
2.Instead of char namerev = name.charAt(namel-i); you have reduce the position one more.
So use: char namerev = name.charAt(namel-1-i);
try something like this:
String s = "stringtotest";
boolean result = true;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != s.charAt(s.length()-1-i)) {
result = false;
break;
}
}
if (result)
System.out.println("Palindrom");
else
System.out.println("Not palindrom");
Same general idea as the others, but I think that this is cleaner and easier to read. Just a thought - everyone has their own style. :) If you're a beginner, I highly suggest getting into the habit of moving redundant logic to its own method. It's cleaner and may prove to be much more useful later.
public class Main {
public static void main( String args[] ) {
for ( String string : args ) {
if ( isPalendrome( string ) {
System.out.println("Palindrome");
} else {
System.out.println("Not a Palindrome");
}
}
}
private static boolean isPalindrome( String string ) {
return string.equals( reverse( string ) );
}
private static String reverse( String original ) {
return new StringBuilder(original).reverse().toString();
}
}
String name="pop"; // string to check if it palindrome or not
String revName="";
int namel = name.length();
for (int i =1; i<=namel; i++)
{
char namerev = name.charAt(namel-i);
revName += namerev;
}
if(name.equals(revName))
{
System.out.println("Palindrome");
}
else
{
System.out.println( "Not a Palindrome");
}
Related
So if I were given a string "Cylinder/soda200/0.0054/5/10" and were to parse it, how would I actually take the parts with just numbers and turn them into an int or double?
Currently I am parsing it by doing this:
String delims="[/]+";
String[] drinkParse=lineToParse.split(delims);
Use Integer.parseInt(), Double.parseDouble() etc, passing your string as an argument.
e.g. int i = Integer.parseInt(drinkParse[3]);
Note that these can throw a NumberFormatException if the argument can't be parsed as requested. (e.g. "soda200" can't parse straight to an int)
You can use new Integer("22") and save it to an int in order to convert it. Same for Double. There are other ways too though, I suggest simple googling.
You should use split function and parse like this
Object[] values = (Object[]) var.split("/");
values[2]=Double.parseDouble(values[2]);
values[3]=Integer.parseInt(values[3]);
values[4]=Integer.parseInt(values[4]);
System.out.println(values);
You can also iterate array and check if string validates against rege/p of double or int and then do corresponding conversion if you dont know positions.
I'm not sure if you're familiar with StringBuilder in java, but you can learn more about it here and you can also take a look at String API here. In the program example below I'm reading character by character from the string you posted until program runs into '/' or unless it's the end of the string. All characters are saved to the StringBuilder and converted into a String after to check if it's a number, either double or integer. If any character in the string is not a number or period isNumber flag value is set to false and we don't print it. In case it's a period we set isDouble flag value to true because we need that information for further conversion. At last we print the numbers if all conditions are true and create new StringBuilder in order to start building a fresh new String.
public class myProject {
public static void main(String[] args) {
String str = "Cylinder/soda200/0.0054/5/10";
StringBuilder sb = new StringBuilder();
boolean isDouble;
boolean isNumber;
System.out.println("List of numbers:");
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != '/') {
sb.append(str.charAt(i));
}
if (str.charAt(i) == '/' || i+1 == str.length()) {
String strConvert = sb.toString();
isDouble = false;
isNumber = true;
for (int j = 0; j < strConvert.length(); j++) {
if (!Character.isDigit(strConvert.charAt(j))) {
if (strConvert.charAt(j) == '.') {
isDouble = true;
} else {
isNumber = false;
}
}
}
if (isDouble && isNumber) {
System.out.println(Double.parseDouble(strConvert));
} else if (isNumber) {
System.out.println(Integer.parseInt(strConvert));
}
sb = new StringBuilder();
}
}
}
}
Hopefully this will help you or anyone else with similar problem!
Please help me to identify my mistakes in this code. I am new to Java. Excuse me if I have done any mistake. This is one of codingbat java questions. I am getting Timed Out error message for some inputs like "xxxyakyyyakzzz". For some inputs like "yakpak" and "pakyak" this code is working fine.
Question:
Suppose the string "yak" is unlucky. Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap.
public String stringYak(String str) {
String result = "";
int yakIndex = str.indexOf("yak");
if (yakIndex == -1)
return str; //there is no yak
//there is at least one yak
//if there are yaks store their indexes in the arraylist
ArrayList<Integer> yakArray = new ArrayList<Integer>();
int length = str.length();
yakIndex = 0;
while (yakIndex < length - 3) {
yakIndex = str.indexOf("yak", yakIndex);
yakArray.add(yakIndex);
yakIndex += 3;
}//all the yak indexes are stored in the arraylist
//iterate through the arraylist. skip the yaks and get non-yak substrings
for(int i = 0; i < length; i++) {
if (yakArray.contains(i))
i = i + 2;
else
result = result + str.charAt(i);
}
return result;
}
Shouldn't you be looking for any three character sequence starting with a 'y' and ending with a 'k'? Like so?
public static String stringYak(String str) {
char[] chars = (str != null) ? str.toCharArray()
: new char[] {};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'y' && chars[i + 2] == 'k') { // if we have 'y' and two away is 'k'
// then it's unlucky...
i += 2;
continue; //skip the statement sb.append
} //do not append any pattern like y1k or yak etc
sb.append(chars[i]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(stringYak("1yik2yak3yuk4")); // Remove the "unlucky" strings
// The result will be 1234.
}
It looks like your programming assignment. You need to use regular expressions.
Look at http://www.vogella.com/articles/JavaRegularExpressions/article.html#regex for more information.
Remember, that you can not use contains. Your code maybe something like
result = str.removeall("y\wk")
you can try this
public static String stringYak(String str) {
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)=='y'){
str=str.replace("yak", "");
}
}
return str;
}
I have to remove leading and trailing spaces from the given string as well as combine the contiguous spaces. For example,
String str = " this is a string containing numerous whitespaces ";
and I need to return it as:
"this is a string containing numerous whitespaces";
But the problem is I can't use String#trim(). (This is a homework and I'm not allowed to use such methods.) I'm currently trying it by accessing each character one-by-one but quite unsuccessful.
I need an optimized code for this. Could anybody help? I need it to be done by today :(
EDIT: Answer posted before we were told we couldn't use replaceAll. I'm leaving it here on the grounds that it may well be useful to other readers, even if it's not useful to the OP.
I need an optimized code for this.
Do you really need it to be opimtized? Have you identified this as a bottleneck?
This should do it:
str = str.replaceAll("\\s+", " ");
That's a regular expression to say "replace any contintiguous whitespace with a single space". It may not be the fastest possible, but I'd benchmark it before trying anything else.
Note that this will replace all whitespace with spaces - so if you have tabs or other whitespace characters, they will be replaced with spaces too.
I'm not permitted to use these methods. I've to do this with loops
and all.
So i wrote for you some little snipet of code if you can't use faster and more efficient way:
String str = " this is a string containing numerous whitespaces ";
StringBuffer buff = new StringBuffer();
String correctedString = "";
boolean space = false;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == ' ') {
if (!space && i > 0) {
buff.append(c);
}
space = true;
}
else {
buff.append(c);
space = false;
}
}
String temp = buff.toString();
if (temp.charAt(temp.length() - 1) == ' ') {
correctedString = temp.substring(0, buff.toString().length() - 1);
System.out.println(correctedString);
}
System.out.println(buff.toString())
Note:
But this is "harcoded" and only for "learning".
More efficient way is for sure use approaches pointed out by #JonSkeet and #BrunoReis
What about str = str.replaceAll(" +", " ").trim();?
If you don't want to use trim() (and I really don't see a reason not to), replace it with:
str = str.replaceAll(" +", " ").replaceAll("^ ", "").replaceAll(" $", "");`
Remove White Spaces without Using any inbuilt library Function
this is just a simple example with fixed array size.
public class RemWhite{
public static void main(String args[]){
String s1=" world qwer ";
int count=0;
char q[]=new char[9];
char ch[]=s1.toCharArray();
System.out.println(ch);
for(int i=0;i<=ch.length-1;i++)
{
int j=ch[i];
if(j==32)
{
continue;
}
else
q[count]=ch[i];
count++;
}
System.out.println(q);
}}
To remove single or re-occurrence of space.
public class RemoveSpace {
public static void main(String[] args) {
char space = ' ';
int ascii = (int) space;
String str = " this is a string containing numerous whitespaces ";
char c[] = str.toCharArray();
for (int i = 0; i < c.length - 1; i++) {
if (c[i] == ascii) {
continue;
} else {
System.out.print(c[i]);
}
}
}
}
If you don't want to use any inbuilt methods here's what you refer
private static String trim(String s)
{
String s1="";boolean nonspace=false;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)!=' ' || nonspace)
{
s1 = s1+s.charAt(i);
nonspace = true;
}
}
nonspace = false;
s="";
for(int i=s1.length()-1;i>=0;i--)
{
if(s1.charAt(i)!=' ' || nonspace)
{
s = s1.charAt(i)+s;
nonspace = true;
}
}
return s;
}
package removespace;
import java.util.Scanner;
public class RemoveSpace {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
System.out.println("Enter the string");
String str= scan.nextLine();
String str2=" ";
char []arr=str.toCharArray();
int i=0;
while(i<=arr.length-1)
{
if(arr[i]==' ')
{
i++;
}
else
{
str2= str2+arr[i];
i++;
}
}
System.out.println(str2);
}
}
This code is used for removing the white spaces and re-occurrence of alphabets in the given string,without using trim(). We accept a string from user. We separate it in characters by using charAt() then we compare each character with null(' '). If null is found we skip it and display that character in the else part. For skipping the null we increment the index i by 1.
try this code to get the solution of your problem.
String name = " abc ";
System.out.println(name);
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == ' ') {
i = 2 + i - 2;
} else {
System.out.print(name.charAt(i));
}
}
This question already has answers here:
Check string for palindrome
(42 answers)
Closed 7 years ago.
I want to check if a string is a palindrome or not. I would like to learn an easy method to check the same using least possible string manipulations
Using reverse is overkill because you don't need to generate an extra string, you just need to query the existing one. The following example checks the first and last characters are the same, and then walks further inside the string checking the results each time. It returns as soon as s is not a palindrome.
The problem with the reverse approach is that it does all the work up front. It performs an expensive action on a string, then checks character by character until the strings are not equal and only then returns false if it is not a palindrome. If you are just comparing small strings all the time then this is fine, but if you want to defend yourself against bigger input then you should consider this algorithm.
boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n/2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
For the least lines of code and the simplest case
if(s.equals(new StringBuilder(s).reverse().toString())) // is a palindrome.
Here is a simple one"
public class Palindrome {
public static void main(String [] args){
Palindrome pn = new Palindrome();
if(pn.isPalindrome("ABBA")){
System.out.println("Palindrome");
} else {
System.out.println("Not Palindrome");
}
}
public boolean isPalindrome(String original){
int i = original.length()-1;
int j=0;
while(i > j) {
if(original.charAt(i) != original.charAt(j)) {
return false;
}
i--;
j++;
}
return true;
}
}
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
Here's a good class :
public class Palindrome {
public static boolean isPalindrome(String stringToTest) {
String workingCopy = removeJunk(stringToTest);
String reversedCopy = reverse(workingCopy);
return reversedCopy.equalsIgnoreCase(workingCopy);
}
protected static String removeJunk(String string) {
int i, len = string.length();
StringBuffer dest = new StringBuffer(len);
char c;
for (i = (len - 1); i >= 0; i--) {
c = string.charAt(i);
if (Character.isLetterOrDigit(c)) {
dest.append(c);
}
}
return dest.toString();
}
protected static String reverse(String string) {
StringBuffer sb = new StringBuffer(string);
return sb.reverse().toString();
}
public static void main(String[] args) {
String string = "Madam, I'm Adam.";
System.out.println();
System.out.println("Testing whether the following "
+ "string is a palindrome:");
System.out.println(" " + string);
System.out.println();
if (isPalindrome(string)) {
System.out.println("It IS a palindrome!");
} else {
System.out.println("It is NOT a palindrome!");
}
System.out.println();
}
}
Enjoy.
public boolean isPalindrom(String text) {
StringBuffer stringBuffer = new StringBuffer(text);
return stringBuffer.reverse().toString().equals(text);
}
I guess this is simple way to check palindrome
String strToRevrse = "MOM";
strToRevrse.equalsIgnoreCase(new StringBuilder(strToRevrse).reverse().toString());
I'm new to java and I'm taking up your question as a challenge to improve my knowledge as well so please forgive me if this does not answer your question well:
import java.util.ArrayList;
import java.util.List;
public class PalindromeRecursiveBoolean {
public static boolean isPalindrome(String str) {
str = str.toUpperCase();
char[] strChars = str.toCharArray();
List<Character> word = new ArrayList<>();
for (char c : strChars) {
word.add(c);
}
while (true) {
if ((word.size() == 1) || (word.size() == 0)) {
return true;
}
if (word.get(0) == word.get(word.size() - 1)) {
word.remove(0);
word.remove(word.size() - 1);
} else {
return false;
}
}
}
}
If the string is made of no letters or just one letter, it is a
palindrome.
Otherwise, compare the first and last letters of the string.
If the first and last letters differ, then the string is not a palindrome
Otherwise, the first and last letters are the same. Strip them from the string, and determine whether the string that remains is a palindrome. Take the answer for this smaller string and use it as the answer for the original string then repeat from 1.
The only string manipulation is changing the string to uppercase so that you can enter something like 'XScsX'
check this condition
String string="//some string...//"
check this...
if(string.equals((string.reverse())
{
it is palindrome
}
public static boolean istPalindrom(char[] word){
int i1 = 0;
int i2 = word.length - 1;
while (i2 > i1) {
if (word[i1] != word[i2]) {
return false;
}
++i1;
--i2;
}
return true;
}
import java.util.Scanner;
public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;
public void allSubstrings(String s){
for(int i=0;i<s.length();i++){
for(int j=1;j<=s.length()-i;j++){
String subString=s.substring(i, i+j);
palindrome(subString);
}
}
}
public void palindrome(String sub){
System.out.println("String to b checked is "+sub);
StringBuilder sb=new StringBuilder();
sb.append(sub); // append string to string builder
sb.reverse();
if(sub.equals(sb.toString())){ // palindrome condition
System.out.println("the given String :"+sub+" is a palindrome");
longestPalindrome(sub);
}
else{
System.out.println("the string "+sub+"iss not a palindrome");
}
}
public void longestPalindrome(String s){
if(s.length()>longest){
longest=s.length();
longestPalindrome=s;
}
else if (s.length()==longest){
oldPalindrome=longestPalindrome;
longestPalindrome=s;
}
}
public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String ::");
String s=sc.nextLine();
fp.allSubstrings(s);
sc.close();
if(fp.oldPalindrome.length()>0){
System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");
}
else{
System.out.println(longestPalindrome+":is the longest palindrome`````");
}}
}
The idea is to have a String read and to verify that it does not contain any numeric characters. So something like "smith23" would not be acceptable.
What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.
Speed
public boolean isAlpha(String name) {
char[] chars = name.toCharArray();
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
Simplicity
public boolean isAlpha(String name) {
return name.matches("[a-zA-Z]+");
}
Java 8 lambda expressions. Both fast and simple.
boolean allLetters = someString.chars().allMatch(Character::isLetter);
Or if you are using Apache Commons, [StringUtils.isAlpha()].
First import Pattern :
import java.util.regex.Pattern;
Then use this simple code:
String s = "smith23";
if (Pattern.matches("[a-zA-Z]+",s)) {
// Do something
System.out.println("Yes, string contains letters only");
}else{
System.out.println("Nope, Other characters detected");
}
This will output:
Nope, Other characters detected
I used this regex expression (".*[a-zA-Z]+.*"). With if not statement it will avoid all expressions that have a letter before, at the end or between any type of other character.
String strWithLetters = "123AZ456";
if(! Pattern.matches(".*[a-zA-Z]+.*", str1))
return true;
else return false
A quick way to do it is by:
public boolean isStringAlpha(String aString) {
int charCount = 0;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (aString.length() == 0) {
return false; //zero length string ain't alpha
}
for (int i = 0; i < aString.length(); i++) {
for (int j = 0; j < alphabet.length(); j++) {
if (aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1))
|| aString.substring(i, i + 1).equals(alphabet.substring(j, j + 1).toLowerCase())) {
charCount++;
}
}
if (charCount != (i + 1)) {
System.out.println("\n**Invalid input! Enter alpha values**\n");
return false;
}
}
return true;
}
Because you don't have to run the whole aString to check if it isn't an alpha String.
private boolean isOnlyLetters(String s){
char c=' ';
boolean isGood=false, safe=isGood;
int failCount=0;
for(int i=0;i<s.length();i++){
c = s.charAt(i);
if(Character.isLetter(c))
isGood=true;
else{
isGood=false;
failCount+=1;
}
}
if(failCount==0 && s.length()>0)
safe=true;
else
safe=false;
return safe;
}
I know it's a bit crowded. I was using it with my program and felt the desire to share it with people. It can tell if any character in a string is not a letter or not. Use it if you want something easy to clarify and look back on.
Faster way is below. Considering letters are only a-z,A-Z.
public static void main( String[] args ){
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(bestWay("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
System.out.println(isAlpha("azAZpratiyushkumarsinghjdnfkjsaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
}
public static boolean bettertWay(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for(char c : chars){
if(!(c>=65 && c<=90)&&!(c>=97 && c<=122) ){
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
public static boolean isAlpha(String name) {
char[] chars = name.toCharArray();
long startTimeOne = System.nanoTime();
for (char c : chars) {
if(!Character.isLetter(c)) {
System.out.println(System.nanoTime() - startTimeOne);
return false;
}
}
System.out.println(System.nanoTime() - startTimeOne);
return true;
}
Runtime is calculated in nano seconds. It may vary system to system.
5748//bettertWay without numbers
true
89493 //isAlpha without numbers
true
3284 //bettertWay with numbers
false
22989 //isAlpha with numbers
false
Check this,i guess this is help you because it's work in my project so once you check this code
if(! Pattern.matches(".*[a-zA-Z]+.*[a-zA-Z]", str1))
{
String not contain only character;
}
else
{
String contain only character;
}
String expression = "^[a-zA-Z]*$";
CharSequence inputStr = str;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputStr);
if(matcher.matches())
{
//if pattern matches
}
else
{
//if pattern does not matches
}
Try using regular expressions: String.matches
public boolean isAlpha(String name)
{
String s=name.toLowerCase();
for(int i=0; i<s.length();i++)
{
if((s.charAt(i)>='a' && s.charAt(i)<='z'))
{
continue;
}
else
{
return false;
}
}
return true;
}
Feels as if our need is to find whether the character are only alphabets.
Here's how you can solve it-
Character.isAlphabetic(c)
helps to check if the characters of the string are alphabets or not.
where c is
char c = s.charAt(elementIndex);
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the https://www.nuget.org/packages/Extensions.cs package to your project.
Add "using Extensions;" to the top of your code.
"smith23".IsAlphabetic() will return False whereas "john smith".IsAlphabetic() will return True. By default the .IsAlphabetic() method ignores spaces, but it can also be overridden such that "john smith".IsAlphabetic(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphabetic().
To allow only ASCII letters, the character class \p{Alpha} can be used. (This is equivalent to [\p{Lower}\p{Upper}] or [a-zA-Z].)
boolean allLettersASCII = str.matches("\\p{Alpha}*");
For allowing all Unicode letters, use the character class \p{L} (or equivalently, \p{IsL}).
boolean allLettersUnicode = str.matches("\\p{L}*");
See the Pattern documentation.
I found an easy of way of checking a string whether all its digit is letter or not.
public static boolean isStringLetter(String input) {
boolean b = false;
for (int id = 0; id < input.length(); id++) {
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
b = true;
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
b = true;
} else {
b = false;
}
}
return b;
}
I hope it could help anyone who is looking for such method.
Use StringUtils.isAlpha() method and it will make your life simple.