I've the below code.
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Dummy {
public static void main(String args[]) throws Exception {
String word="hi";
String[] one={"a","b","c"};
String[] two={"d","e","f"};
String[] three={"g","h","i"};
String[] four={"j","k","l"};
String[] five={"m","n","o"};
String[] six={"p","q","r","s"};
String[] seven={"t","u","v"};
String[] eight={"w","x","y","z"};
for(int i=0;i<word.length();i++)
{
for(int j=0;j<three.length;j++)
{
if(three[j].equals(word.charAt(i)))
{
System.out.println("Matched");
}
else
{
System.out.println("err");
}
}
}
}
}
Here my concept is to match a letter from the string to the array created and here the output is all err(condition stating not matched). please let me know where am i going wrong.
Thanks
You're comparing a single-character string (from your arrays) to a character. Make your arrays of char, not String. (And use == to compare them.)
The element three[j] in for loop is String whereas word.charAt(i) is char.. so equals() against those will be always false.
You should either change it to
if(three[j].equals(String.valueOf(word.charAt(i))))
so that it compares string's actual context, or define arrays (one, two, three.. ) to be char array instead of string array so that you can simply use == for that.
Please check equals() for String, Object, and the others in JavaDoc, and probably you need to check hashCode() as well to fully understand what's equals() means in Java.
charAt return a char not a string so it can't be "equals" to a String
Why don't you use String.indexOf() ?
for(int j=0;j<three.length;j++)
{
if(word.indexOf(three[j]) == -1)
{
System.out.println("err");
}
else
{
System.out.println("Matched");
}
}
This way you will enter in a single loop..
Try like this:
StringBuffer result = new StringBuffer();
for (int i = 0; i < one.length; i++) {
result.append(one[i]);
}
if (result.toString().equals(word)) {
System.out.println("Matched");
} else {
System.out.println("err");
}
Just saying the obvious....sometimes it is helpful to see the actual code. Following is excerpt from java.lang.String
See bold condition in particular. it returns false if instanceof fails!
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (**anObject instanceof String**) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
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´m a bloody beginner trying to write a lil programm to check if 2 words are anagrams. So far all the whitespaces within the words get deleted but apparently there's an error with my Arrays.sort() but I can´t see it. Why and where´s the error in my Arrays.sort() line and how could I solve it?
Edit: If I leave the Arrays.sort() out like this it compiles and works so apparently there's only a problem with that line. If I leave them in it points to array and says error: can not find symbol
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
int word1 = w1.length();
String w2 = wordTwo.replaceAll("\\s", "");
int word2 = w2.length();
boolean anagrammStatus = false;
if(word1 == word2)
{
anagrammStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
//Arrays.sort(charArrayWordOne);
//Arrays.sort(charArrayWordTwo);
anagrammStatus = charArrayWordOne.equals(charArrayWordTwo);
}
if(anagrammStatus == false)
{
System.out.println("Anagram");
}
else;
{
System.out.println("No Anagram");
}
}
This should do the trick:
public static void isAnagramm(String wordOne, String wordTwo)
{
String w1= wordOne.replaceAll("\\s", "");
String w2 = wordTwo.replaceAll("\\s", "");
// No need to keep the length variables
boolean anagramStatus = false;
// Check if the strings are equal to begin with, use equals and not == operator
if(w1.equals(w2))
{
anagramStatus = true;
}
else
{
char [] charArrayWordOne = w1.toLowerCase().toCharArray();
char [] charArrayWordTwo = w2.toLowerCase().toCharArray();
Arrays.sort(charArrayWordOne);
Arrays.sort(charArrayWordTwo);
// Compare arrays using the Arrays.equals method to avoid comparing the object references
anagramStatus = Arrays.equals(charArrayWordOne, charArrayWordTwo);
}
// Use simple boolean logic in your condition here, or again, always use == instead of =
if (anagramStatus)
{
System.out.println("Anagram");
}
else
{
System.out.println("No Anagram");
}
}
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 using this code, to get the index of a String in an Array.
int n = Arrays.asList(Names).indexOf(textBox.getText());
The problem here is, if the String in textBox is different in case to its similar String in the Array. It returns -1. How can make it something like equalsIgnoreCase in case of String comparision.
Thank You
You can use the Collator class. in Here you can set different levels for your comparison.
you can ignore lower and upper cases, and set some specific language charackters. In German for example it can set ß equal to ss.
here´s some documentary:
Collator class
Edit : here´s an example Code for you
private int indexOf(String[] original, String search) {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.SECONDARY);
for(int i = 0;i<original.length;++i) {
if(collator.equals(search, original[i]))
return i;
}
return -1;
}
You can use StringUtils class of Apache commons libraries or this If you don't want to download the library look at the source code for logic to create the method. The stackoverflow link for using StringUtils
If you want to find the index of String from array of strings then there is another library ArrayUtils which has a method indexOf
here's the implementation of indexOf
public static int indexOf(Object[] array, Object objectToFind, int startIndex) {
if (array == null) {
return INDEX_NOT_FOUND;
}
if (startIndex < 0) {
startIndex = 0;
}
if (objectToFind == null) {
for (int i = startIndex; i < array.length; i++) {
if (array[i] == null) {
return i;
}
}
} else {
for (int i = startIndex; i < array.length; i++) {
if (objectToFind.equals(array[i])) {
return i;
}
}
}
return INDEX_NOT_FOUND;
}
since you can see that it uses .equals() I suggest you to
1) create a custom string class
2) add it to the array
3) override the .equals method like this
class StringCustom
{
String string;
//implement getters and setters
public String equals(Object o)
{
return this.getString().equalsIgnoreCase(((String)o).getString());
}
}
A different approach where internally make sure ignore case.
public static int indexOfIgnoreCase(String[] strs, String text){
int n = strs.length;
for(int i=0;i<n;i++){
if(strs[i].equalsIgnoreCase(text))
return i;
}
return -1;
}
int n = indexOfIgnoreCase(Names,textBox.getText());
You can extend ArrayList in this way
public class StringArrayList extends ArrayList<String> {
#Override
public boolean contains(Object o) {
String paramStr = (String)o;
for (String s : this) {
if (paramStr.equalsIgnoreCase(s)) return true;
}
return false;
}
public int indexOf(Object o) {
String paramStr = (String)o;
int index = 0;
for (String s : this) {
if (paramStr.equalsIgnoreCase(s)) return index;
index++;
}
return -1;
}
}
Eventually :
int n = new StringArrayList(Arrays.asList(Names)).indexOf(textBox.getText());
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.