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.
Related
Example: String a = "ACAHBBA" and String b = "ABAB" should return true, since both strings can spell ABAB.
I have tried with contains(), but that only works for equal sequences.
// The code should look like this.
public class task10 {
public static boolean contains(String a, String b) {
// check if b can be spelled using characters from a.
// if it can. return true.
// else
return false;
}
}
Posible solution?
public static boolean contains(String a, String b) {
for (int i = 0; i < b.length(); i++) {
if (a.indexOf(b.charAt(i)) == -1) {
return false;
}
}
return true;
}
Simply iterate thru one string and get the index of the character. If >= 0, replace character with non-alphabetic character and repeat. This algorithm presumes the need to match the correct number of characters. For example, hello would return false if the character set was helo.
public static boolean spelledFrom(String word, String chars) {
StringBuilder sb = new StringBuilder(chars);
for (String c : word.split("")) {
int i;
if ((i = sb.indexOf(c)) < 0) {
return false;
}
sb.setCharAt(i, '#');
}
return true;
}
You can try this:
public static boolean canSpell(String a, String b)
{
String shorter = (a.length() <= b.length()) ? a : b;
String longer = (shorter.equals(a)) ? b : a;
for(int i = 0; i < shorter.length(); i++)
{
if(!longer.contains("" + shorter.charAt(i)))
return false;
}
return true;
}
Once you've identified the shorter string, you just need to verify that each of its chars are contained in the longer string. This solution doesn't verify if a char "has already been used", which means inserting "AB" and "ABBA" will return true. If you need to do this, you just need to delete the verified char from the longer string in every loop.
I have to make a method named 'contains' that accepts a string and a character as parameters and returns true if that character occurs two or more times in the string.
example: Input contains("Apple", 'p') should return "True"
private boolean contains(String a,char b) {
if(a.contains(b)) {
print("true");
}
else {
print("");
}
//boolean c = a.contains('l');
return false;
}
I know this code is wrong ... I want to know what I have to do and what I have to fix .
I would appreciate your advice
Thank you.
There are a few ways to do this but the simplest would just be to loop through the String looking for the char, if count reaches two then return true.
For this consider using
for (char c : input) {
if (c == myChar) count++;
if (count >= 2) return true;
}
return false;
Another way would be to use String.replace and replace the wanted char with ""
then compare the size of the before and after String
Your method may return a boolean based on the size difference between the original string, and the string without the given character :
return (a.length() - (a.replace(b, '')).length()) >= 2 ;
In theoretical terms:
First: you need to iterate over the input string characters using a for loop and then in each iteration compare the current character in the string with the other character argument which is given as method argument. If they match, then you can increase a counter (a variable). Then compare if the counter value is 2 and return true immediately it is so. At the method end you can return false just like you have done already.
Second : you are printing true , not returning true. Should use return true; when the value of variable becomes 2
countMatches(a,b) returns the count of b in String a. and it is from org.apache.commons.lang3
private boolean contains(String a,char b) {
return StringUtils.countMatches(a, b)>=2 ;
}
or in simple java you can use
private boolean contains(String a,char b) {
return (a.length() - a.replaceAll(String.valueOf(b),"").length())>=2 ;
}
This is one of simple ways to do this. Here the string is put into char array. This way it is easier to examine the elements of the char array and find out same characters.
private boolean contains(String a, char b) {
char[] c_array = a.toCharArray();
int count = 0;
for (int i = 0; i < c_array.length; i++) {
if (b == c_array[i]) {
count++;
continue;
} else {
continue;
}
}
if (count >= 2) {
return true;
} else {
return false;
}
}
public class Demo {
public static boolean contains(String str,char c){
//todo:check str for NullPointExecption
int flag=0;
for(int i=0;i<str.length();i++){
if(c==str.charAt(i)){
flag++; //if str contains char c,flag=flag+1
}
if(flag>=2){
return true; //if flag>=2,return true
}
}
return false;
}
public static void main(String[] args) {
System.out.println(contains("appple", 'p'));//result is true
}
}
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");
}
For the code i need to write a method the decompresses a string. For example if the user entered "2d5t" the method would return "ddttttt". My code now will work for that input but if the input uses a character without a number before it the program wont work when it should. For example if the input was just "d" the program wouldnt work instead of just returning "d". The code also has to be recursive.
Here is what my code is now please help.
public static String decompress(String compressedText) {
if (compressedText.equals(""))
return "";
return decompress(compressedText, charInt(compressedText, 0), 0);
}
public static String decompress(String text, int count, int pos) {
if (pos == text.length() || (pos == text.length()-2 && count == 0))
return "";
else if (count == 0)
return decompress(text, charInt(text, pos+2), pos+2);
return text.charAt(pos+1) + decompress(text, count-1, pos);
}
public static int charInt(String str, int idex) {
return str.charAt(idex) - '0';
}
Here's some pseudocode:
function createString(int times, char character){
if times is 0, do nothing
otherwise return character + createString(times-1, character);
}
function createString(string full){
split string by number/character pairs
for each pair, call createString(times, character), and append them
}
I don't believe in handing out real code, sorry. It's much better in the long run.
You need to validate your user input. Decide first, that what string values are acceptable to your method and then write a validate method. Then invoke that method inside your decompress method.
Look into string manipulation functions and regular expressions in Java. And then try rewriting your code.
As mentioned by others, this can be solved with regular expressions. An example solution is:
public static String decompress(String compressed) {
Matcher matcher = Pattern.compile("(\\d+)([^\\d])").matcher(compressed);
StringBuffer decompressed = new StringBuffer();
while (matcher.find()) {
Integer charNum = Integer.parseInt(matcher.group(1));
StringBuilder decompressedChars = new StringBuilder();
for (int i = 1; i <= charNum; i++) {
decompressedChars.append(matcher.group(2));
}
matcher.appendReplacement(decompressed, decompressedChars.toString());
}
matcher.appendTail(decompressed);
return decompressed.toString();
}
This code won't support numbers larger than Integer.MAX_VALUE and you might want to put some error handling and validation in there also.
**Edited to be recursive as per the OP's request
Tested left first one char lookahead parser using regex
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Parser{
private static String parse(StringBuilder output, String input, Integer offset){
if(offset<input.length()){
java.util.regex.Pattern p0 =
java.util.regex.Pattern.compile("\\d(?=[a-z])");
java.util.regex.Pattern p1 =
java.util.regex.Pattern.compile("[a-z]");
java.util.regex.Matcher m0 = p0.matcher(input);
java.util.regex.Matcher m1 = p1.matcher(input);
if (m0.find(offset) && m0.start() == offset)
{
for(Integer i = 0;
i < Integer.parseInt(String.valueOf(input.charAt(offset)));
++i) {
output.append(input.charAt(offset+1));
}
offset+=2;
}
else if (m1.find(offset) && m1.start() == offset) {
output.append(input.charAt(offset));
++offset;
}
else {
++offset;
}
return parse(output, input, offset);
}
else return output.toString();
}
public static void main(String[] args)
{
Integer offset = 0;
StringBuilder output = new StringBuilder();
parse(output, args[0], offset);
System.out.println(output.toString());
}
}
I have problem with two of my methods for password validation.
The method hasDigitsAndLetters is supposed to check whether all the characters of the String are digits and letters and the second method hasTwoDigits is supposed to check whether there are at least two digits in the pass, but the problem is that for expected result true they are ruturning false. If someone can help. here is the code.
//check if the whole string consists of digits and letters
public static boolean hasDigitsAndLetters(String pass)
{
for(int i=0; i<pass.length(); i++)
{
if(!Character.isLetterOrDigit((i)))
{
return false;
}
}
return true;
}
// check whether the password has at least 2 digits
public static boolean hasTwoDigits(String pass)
{
int counter = 0;
for(int i=0; i<pass.length(); i++)
{
if(Character.isDigit(i))
{
counter ++;
}
}
System.out.println("Number of digits: " + counter);
if(counter >= 2)
{
return true;
}
return false;
}
You need to pass character at position i for that String.
Character.isLetterOrDigit((pass.charAt(i)))
same for digit also
Character.isDigit((pass.charAt(i)))
You want to check the character in the string at index i, not the index variable itself:
Character.isLetterOrDigit(pass.charAt(i))
You aren't checking against characters in your pass, you need to change your checks to:
if(!Character.isLetterOrDigit((pass.charAt(i)))
and
if(Character.isDigit(pass.charAt(i)))
Right now you are checking if i is a digit or letter and i is an int. You need to check the character at position i.
if(Character.isDigit(pass.charAt(i)))
The error is that you're comparing the position into the string rather than the character at that position in the string. I'd probably not use charAt, however... there's no point in keeping explicit management of the position here. I suggest you use String.toCharArray instead.
public static boolean isAlphanumeric(final String str) {
for (char c : str.toCharArray()) {
if (!Character.isLetterOrDigit(c)) {
return false;
}
}
return true;
}
public static boolean isBidigital(final String str) {
int n = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
++n;
}
}
return n >= 2;
}