First of all, the example you provided is not a String array. It is a String.
I am giving the solution based on String. If you need it for String array, you will be able to do this on your own, if you understand this.
First, lets take a string tokenizer. A tokenizer breaks apart a string by a given character set. In its simplest form, it breaks apart a string by space.
For example, a string str = "This is a test". A simple tokenizer will break this string into words like "This" "is" "a" "test".
Below is the code to declare and use tokenizer:
StringTokenizer st = new StringTokenizer(a); // a is given your string
Now, we declare an array of string below. (An array of string is an array, the element of each array is a single string.)
String[] str_arr = new String[100];
We will now use the tokenizer to get each word of your string and keep each words in the array of strings like below:
int index=0; // to keep track of index of the array (of strings)
while (st.hasMoreElements()) {
str_arr[index] = (String) st.nextElement();
index++;
}
So, now we have an array of strings named 'str_arr'. Now we will check for each element of the array whether duplicate values are occuring or not. If we find a duplicate, we will replace it with a null value. But, we will do it only once. The remaining duplicates will be kept as it is, this is what you asked for, right?
To keep track of a string already searched and made null, we will use a HashMap like this.
HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
Now, we will run 2 nested loops and after that, we will have a modified array where only multiple occurrence of a string is reduced by 1.
for(int i=0; i<index; i++){
String current_string = str_arr[i];
for(int j=i+1; j<index; j++){
if( (current_string.equals(str_arr[j])) && (hash_map.containsKey(current_string)==false) && str_arr[j]!=""){
hash_map.put(str_arr[j], 1);
str_arr[j]="";
break;
}
}
}
Now, you can print all the words simply as below:
for(int i=0; i<index; i++)
System.out.print(str_arr[i]+" ");
INPUT: This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty.
OUTPUT: This is a life and our will be full of fun just like the Benn Steller's Secret life Walter Mitty.
Sorry for long explanation, but still if you can't get any point, please comment. I will try to reply.
Thanks!
Happy Coding :)
Array!!!