String str1 ="India is a great country";
String str2 = "Isgt";
Output: ndarecouy
Could you please help me anyone.
This is i tried
public static void main (String [] arg) {
String str1 ="India is a great country";
String str2 = "Isgt";
// Expected output = ndarecouy
String result ="";
for(int i =0 ; i <str2.length(); i ) {
String value1 = String.valueOf(str2.charAt(i));
for (int j = 0; j< str1.length() ; j ) {
String value2 = String.valueOf(str1.charAt(i));
if (value1.equalsIgnoreCase(value2)) {
} else {
result = value2;
}
}
}
System.out.println("My program return this output: " result);
}
My program return this output: nnnnnnnnnnnnnnnnnnnnnnnnddddddddddddddddddddddddiiiiiiiiiiiiiiiiiiiiiiii
CodePudding user response:
The outer loop should be iterating through the characters of str1
not str2
. And in the inner loop you mistakenly use i
rather than j
as the index. However, even with those changes the algorithm would not be correct.
What you need to do is iterate through each character in str1
and only add each character to result
if it is not found in str2
and not found in result
. You could do this using inner loops, but using indexOf
or contains
would be simpler.
I have posted an example solution below, but I recommend you do not study it until you have spent several hours trying to solve the problem yourself.
public static void main(String[] arg) {
String str1 = "India is not a bad country";
String str2 = "Isgt";
String result = "";
String str2Lower = str2.toLowerCase();
for (int i = 0; i < str1.length(); i ) {
char value1 = Character.toLowerCase(str1.charAt(i));
if (!Character.isSpaceChar(value1)
&& str2Lower.indexOf(value1) == -1
&& result.indexOf(value1) == -1) {
result = value1;
}
}
System.out.println("My program return this output: " result);
}