In: Computer Science
In java P4.7 Following Section 4.9, develop a program that reads a string and removes all duplicates. For example, if the input is Mississippi, print Misp. Start small and just print the first letter. Then print the first letter and true if the letter is not duplicated elsewhere, false otherwise. (Look for it in the remaining string, by using the substring and indexOf method). Next, do the same for the first two letters, and print out for each letter whether or not they occur in the substring before and after the letter. Try with a string like oops. Extend to all characters in the string. Have a look at the output when the input is Mississippi. Which character should you not report? At this time, you should have gathered enough experience that you can complete the program.
Explanation : first i am taking input from console object and then passing the string with its lenth to the removeDuplicate method and in this method we will find the duplicate character and if find remove from string and store in a different array and then return this .
import java.util.*;
import java.io.*;
public class Main
{
static String removeDuplicate(char str[], int n)
{
// Used as index in the modified string
int index = 0;
// Traverse through all characters
for (int i = 0; i < n; i++)
{
// Check if str[i] is present before it
int j;
for (j = 0; j < i; j++)
{
if (str[i] == str[j])
{
break;
}
}
// If not present, then add it to
// result.
if (j == i)
{
str[index++] = str[i];
}
}
return String.valueOf(Arrays.copyOf(str, index));
}
// Driver code
public static void main(String[] args)
{
Console console = System.console();
String str1 = console.readLine("Enter string :");
char str[] = str1.toCharArray();
int n = str.length;
System.out.println(removeDuplicate(str, n));
}
}
output :