Problem:
Write a program that read a string str and prints a string obtained from str by removing/ignoring duplicates. For example, if str is abbacdcae, then your program prints abcde. In other words, only the first occurrence of a character is printed.
Solution:
import java.util.Scanner;
public class lauprob3
{
public static void main(String[] args)
{
//First off, let's scan our string
Scanner scan = new Scanner (System.in);
String string = scan.nextLine();
//We're gonna be looping over each character in the String
for (int x = 0; x < string.length(); x++)
//We're gonna loop over every character of the String
//that comes after the character from the outer/first loop
for (int y = x+1; y <= string.length()-1; y++)
{
//We're gonna check if any of the characters after x
//ie the characters from this second loop, are the same as
//as x so that we'll remove x's duplicates
if (string.charAt(x) == string.charAt(y))
{
//If we find that x and y are equal
//then we're going to make our string equal to
//itself but without the y character through using
//substrings that pass over y
//Note: substring(a,b) means from a to b but only including a
string = string.substring(0,y)+ string.substring(y+1,string.length());
//We need to get rid of an extra increment because we
//deleted a repeated character
y--;
}
}
System.out.println(string);
}
}