This question already has answers here:
In Java, how do I check if a string contains a substring (ignoring case)? [duplicate]
(6 answers)
Closed 9 years ago.
I am writing a program to compare a few characters with a Char Array and return the index of the array. Is there any possible way to compare ignore case?
For example below:
String in = "I AM A HAPPY BOY";
char[] cha = new char[] {a,c,e,g,i,k,h,m,o,q,s,u,w,y};
char testChar = in.substring(4,5).charAt(0);
for(int a = 0; a<char.length; a++){
if(cha[a] == testChar)
return a+1;
}
I am unable to get the index as it will always point to 0. Is there anyway to ignore case here? Appreciate some advise.
Use Character.toLowerCase on both characters:
if (Character.toLowerCase(cha[a]) == Character.toLowerCase(testChar)) {
// logic here
}
As a side note, you could get away with the first toLowerCase if all the characters in your array are already lower case, or even use toLowerCase on the initial string and avoid both.
You can use Character.toLowerCase(char):
if (Character.toLowerCase(cha[a]) == Character.toLowerCase(testChar)) {
return a+1;
}
use Character.ToLowerCase(char c) before testing for equality.
in=in.toLowerCase();
However the most efficient way to convert chars between cases is to flip the 6th bit (ASCII values differ by 32).
Related
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have trouble with my code. I need to replace element in Array if condition is true.
Inputs are:
dashedCapital = "------";
input = "a";
capital = "Warsaw";
Code should check if capital contains input and if yes replace "-" in dashedCapital to character from input at specified position:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
String[] capitalArray = capital.split("");
String[] dashedCapitalArray = dashedCapital.split("");
String[] character = input.split("");
for(int i = 0; i < capitalArray.length; i++){
//System.out.println(i);
//System.out.println(capitalArray[i] + character[0] + dashedCapitalArray[i]);
if(capitalArray[i] == character[0]){
dashedCapitalArray[i] = character[0];
}
}
String result = Arrays.toString(dashedCapitalArray);
System.out.println(result);
return result;
}
Result is "------" but should be "-a--a-". What's going wrong?
John, thanks for your reply, it was helpful.
I edited my method so it's look like this now:
public static String changeDashedCapital(String dashedCapital, String input, String capital){
for(int i = 0; i < capital.length(); i++){
if(capital.charAt(i).equals(input.charAt(0))) {
String new_dashed = dashedCapital.substring(0,i)+input.charAt(0)+dashedCapital.substring(i);
System.out.println(new_dashed);
}
}
return "OK:";
Now i get this error:
GetWord.java:69: error: char cannot be dereferenced
if(capital.charAt(i).equals(input.charAt(0))) {
^
1 error
I don't understand why it's wrong. I using a equals() function. I also tried "==" operator but then nothing happens. What does it mean "char cannot be dereferenced"? How I could compare single chars from string with another chars from another string?
The reason it is not working is because your if for character equality is never true. You’re comparing strings of length 1 and not characters. You can quickly fix by changing if be using the string comparing function .equals()
if(capitalArray[i].equals(character[0])){
...
}
However, you should change your code and not just use this fix. Don’t split your stings into arrays, just use the .charAt() method to get a character at a particular index.
This question already has answers here:
What's the best way to check if a character is a vowel in Java?
(5 answers)
Closed 6 years ago.
I was trying to grab the first character from user entry, and determine it to be a vowel or not. I am very new, and have been struggling with this for a while. I am trying to add all vowels to the variable 'vowel', and not only will that obviously not work, but I feel like I am going the long way. Any help at all is vastly appreciated as I am very new to this.
entry = scanner.nextLine();
letters = entry.substring(0,1);
holder = entry.substring(1);
vowels = "A";
if (entry.substring(0,1).equals(vowels)) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}
First, since you only want one character, don't use string methods, i.e. use entry.charAt(0) == 'A' instead of entry.substring(0,1).equals("A").
With that, you can then turn it around:
"AEIOU".indexOf(entry.charAt(0))
If the character at position 0 in the entry variable can be found, indexOf() returns the index position (zero-based), otherwise it returns -1.
So, to see if it is a vowel, do this:
if ("AEIOU".indexOf(entry.charAt(0)) != -1) {
pigLatinVowel = entry + "way";
System.out.println(pigLatinVowel);
}
This question already has answers here:
How can I get a char array in reverse order?
(10 answers)
Closed 7 years ago.
Question of reverse string without using string function
I didn't get the inner for loop why s.length()-1 ? why -1 ?
its something have to do like multi dimensional arrays?
char ch[]=new char[s.length()];
for(i=0;i < s.length();i++)
ch[i]=s.charAt(i);
for(i=s.length()-1;i>=0;i--)
System.out.print(ch[i]);
found this code but
The indices of a Java String's characters go from 0 to the String's length - 1 (just like the indices of a Java array start in 0, so do the indices of a String).
Therefore in order to print the String in reverse order, the second loop iterates from s.length()-1 to 0. Prior to that, the first loop iterates from 0 to s.length()-1 in order to copy the characters of the String to a character array.
This has nothing to do with multi-dimensional arrays.
I know you asked for the iterative solution explanation. But, I'll give you the recursive explanation.
public static String reverse(String str)
{
if ((str == null) || (str.length() <= 1))
return str;
return reverse(str.substring(1)) + str.charAt(0);
}
Basically, you check every time the str before calling the function. This is called the base case and is used to stop when the job is completed and not get a stack overflow.
Then, afterwards, the functions returns just a section of the original function. At the end, you'll get the str completely reversed as the iterative solution.
Try using the function using System.out.println(reverse("hello"));
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm trying to write a simple hangman game in java for my college class. For some reason the if statement never returns seems to think that the two substrings being compared are equal. The two print statements show that by all rights the two should equate.
public String guessLetter(String letter)
{
String blanks = "";
String theWord="FOO";
for(int i=0; i<=theWord.length()-1; i++)
{
System.out.print(letter.substring(0,1).toUpperCase());
System.out.print(theWord.substring(i,i+1)+ "\n");
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1)))
{
blanks = blanks + theWord.substring(i,i+1);
}
else
{
blanks = blanks + "___ ";
}
}
return blanks;
}
EDIT - As a great many people have pointed out, when comparing Strings, one must use the equals method instead of ==. I was unaware.
You are comparing a String so use "String".equals() dont use ==
use like this:
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
Java dont have == for string
you must use string1.equals(string2) function
if((letter.substring(0,1).toUpperCase())==(theWord.substring(i,i+1))) \ this is wrong for strings
When you compare strings you should use .equals or .equalsIgnorecase
if((letter.substring(0,1).toUpperCase()).equals(theWord.substring(i,i+1)))
ans also checkout the difference between == and .equals in java good explanation is given there.
This question already has answers here:
Converting to upper and lower case in Java
(6 answers)
indexOf Case Sensitive?
(19 answers)
Closed 8 years ago.
String s ="Ganesh";
System.out.println(""+s.indexOf("ga"));
System.out.println(""+s.indexOf("Ga"));
When I run this, I get -1 for s.indexOf("ga") and 0 for s.indexOf("Ga")
I want to get 0 for both.
How to achieve this?
Unfortunately, there is no indexOfIgnoreCase() method, but you can achieve the same with using toLowerCase().
System.out.println(""+s.toLowerCase().indexOf("ga"));
You can convert the string you're looking for to lower or upper case when using indexOf, this way you'll always get the correct index regardless of casing
String s = "Ganesh";
String s2 = "ga";
String s3 = "Ga";
System.out.println(s.toLowerCase().indexOf(s2.toLowerCase()));
System.out.println(s.toLowerCase().indexOf(s3.toLowerCase()));
> 0
> 0
You can even put it into your own method like this:
public int indexOfIgnoreCase(String s, String find) {
return s.toLowerCase().indexOf(find.toLowerCase());
}
Then you can use it like this:
String s = "Ganesh";
System.out.println(indexOfIgnoreCase(s, "ga"));
System.out.println(indexOfIgnoreCase(s, "Ga"));
> 0
> 0
use the toLowerCase() or the toUpperCase() method of the String class, before you use the indexOf().
To use indexOf case-insensitive you can convert the Strings to lowercase first:
System.out.println("" + s.toLowerCase().indexOf("ga".toLowerCase()));
System.out.println("" + s.toLowerCase().indexOf("Ga".toLowerCase()));