1

I have a string array

String a = "This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty.";

String a1[]=a.split(" ");
for(String temp: a1)
{
    System.out.println(temp);
}

Here "life" is repeated three times. Now I have to remove only one frequency of duplicate word form array.

please guide me....

Thanks.

8
  • 3
    this is not an Array!!! Commented Jun 23, 2014 at 6:15
  • does this code even compile?. You will get String cannot be converted to String[] error Commented Jun 23, 2014 at 6:15
  • 1
    Not clear what you want to do here. It would help if you can post the final string you want. That would make it easier for us to answer Commented Jun 23, 2014 at 6:16
  • what do you mean about one frequency of duplicate? Commented Jun 23, 2014 at 6:19
  • 1
    Edit the question so it does not say a String array. Format the code a bit so people can see it better. Specify your issue (What's "one frequency of duplication"?) and bold it. Commented Jun 23, 2014 at 6:22

4 Answers 4

2

You can use something like this, but this will remove only first occurence of specified word:

Full code which removes one duplicate. You need to know that it doesn't ignore special characters, and space is delimiter in this case.

public static void main(String []args){
     String a = "This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty Mitty";
     System.out.println(removeOneDuplicate(a));
}

public static String removeOneWord(String str, String word){
    int value = str.indexOf(word);
    String result = str.substring(0, value);
    result += str.substring( value+word.length(), str.length());
    return result;
}

public static String removeOneDuplicate(String a){
    String [] tmp = a.split(" ");
     Map<String, Integer> map = new HashMap<String, Integer>();
     for(String s: tmp){
         if( map.containsKey(s)){
            int value = map.get(s); 
            if(value == 1)
                a = removeOneWord(a, s);
             map.put(s, value + 1);
         }
         else
             map.put(s, 1);
     }
     return a;
}

Sample results:

INPUT: This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty Mitty
OUTPUT: This is a  and our life will be full  fun just like the Benn Steller's Secret life of Walter  Mitty

In result You can see that life, of and Mitty is removed.

EDIT

If you want to remove all duplicates and leave first occurence of word change following lines:

int value = str.indexOf(word); -> int value = str.lastIndexOf(word);

int value = map.get(s); 
if(value == 1)
    a = removeOneWord(a, s);
map.put(s, value + 1);

to:

a = removeOneWord(a, s);
Sign up to request clarification or add additional context in comments.

8 Comments

It's not answering the question. It removes a specified word, but not "one frequency of duplicate word", and definitely not duplicate.
could you explain what he meant by saying one frequency of duplicate ?
I hope this is what OP wanted.
the output is totally wrong because it removes a first life and keep the rest. It must keep the first and remove the rest.
It's very simple to acheive that, but I'm not sure if it is what OP's wanted. Remove if(value == 1) and change str.indexOf(word) to str.lastIndexOf(word) and you will get that.
|
0

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 :)

3 Comments

how were you able to keep all life and just remove ofs?
About "life" => I removed 1 life from the 3 occurrences , About "of" => I removed 1 of from the 2 occurrences. This is what you asked for, right?
but your output showed the difference. could u check out my answer too? but I didn't remove any of cuz the question doesn't ask :)
0

As we know, set does not contain duplicate at all.

My Code:

 String a = "This is a life and our life will be full of fun just like the Benn     Steller's Secret life of Walter Mitty.";
        String[] aSpilt = a.split(" ");

        List<String> list = Arrays.asList(aSpilt);
        System.out.print("The input is : ");
        list.forEach((s) -> System.out.print(s + " "));
        System.out.println();
        Set<String> noDuplicateSet = new LinkedHashSet<>();
        Set<String> duplicateSet = new LinkedHashSet<>();

        list.forEach((i) -> {
            if (!noDuplicateSet.add(i) && i.equals("life")) {
                duplicateSet.add(i + " ");
            }
        });
        System.out.print("The output is : ");
        noDuplicateSet.forEach((s) -> System.out.print(s + " "));
        System.out.println("");
        duplicateSet.forEach((s) -> System.out.print(s + " "));

My output:

The input is : This is a life and our life will be full of fun just like the Benn Steller's Secret life of Walter Mitty. 
The output is : This is a life and our will be full of fun just like the Benn Steller's Secret Walter Mitty

Note:

  1. I kept the first life and remove the rest, and of was encountered more than once which I did not touched because the question wants just to keep first life and remove the rest.

  2. I used lambda expression to traverse collections

Sources:

  1. http://www.programcreek.com/2013/03/hashset-vs-treeset-vs-linkedhashset/

  2. http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Comments

0
public static void main(String args[])
{
    String  s;
    Scanner in=new Scanner(System.in);
    s=in.nextLine();
    String ch[]=s.split(" ");
    String m=in.nextLine();
    for(int i=;i<ch.length;i++)
    {
        if(ch[i].matches(m))
            ch[i]="";

        S.o.p(ch[i]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.