public class removeduplicatesfromstring {
public static void main(String[] args) {
String str = "manishaam";
//String finalstring="";
char newarr[]= new char[str.length()];
for(int i=0;i<str.length(); i++)
{
char fl= str.charAt(i);
for(int j=0;j<str.length();j++)
{
char fs= str.charAt(j);
if(fl!=fs)
{
newarr[i]= str.charAt(i);
}
}
}
System.out.println(newarr);
}
}
Instructor
Yogesh Chawla Replied on 05/11/2019
You can use this:
public static void main(String[] args) {
String input = "manishaam";
String output = "";
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index % input.length()) != input
.charAt((index + 1) % input.length())) {
output += input.charAt(index);
}
}
System.out.println(output);
}
There is a problem in which you are traversing the second for loop
Instructor
Yogesh Chawla Replied on 05/11/2019
Or Y
public static void main(String[] args) {
String input = "manishaam";
String result = "";
for (int i = 0; i < input.length(); i++) {
if (!result.contains(String.valueOf(input.charAt(i)))) {
result += String.valueOf(input.charAt(i));
}
}
System.out.println("Output is " + result);
}
ou can use this as well:
Instructor
Yogesh Chawla Replied on 05/11/2019
Or simply use LinkedHashSet. That will remove duplicates like this:
public static void main(String[] args) {
String string = "manishaam";
char[] chars = string.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for (char c : chars) {
charSet.add(c);
}
StringBuilder sb = new StringBuilder();
for (Character character : charSet) {
sb.append(character);
}
System.out.println(sb.toString());
}