Click here to Skip to main content
15,564,399 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I hope you got my question - !
I expect output -
[Mahendra, Singh, Dhoni, Virat, Singh, Tracktor, Mahendra]
The dupli Strings are -
Mahendra
Singh 


What I have tried:

package Functions;
import java.util.*;
import java.util.Arrays;
public class stringString {
public static void main(String[] args) {
String name = "Mahendra Singh Dhoni Virat Singh Tracktor Mahendra";
String[] arr = name.split(" ");
System.out.println(Arrays.toString(arr));
System.out.println("The dupli Strings are - ");
for(int i=0;i<arr.length;i++) {
	for(int j=i+1;j<arr.length;j++) {
		if(arr[i]==arr[j]) {
			System.out.println(arr[j]);
				}
			}
		}
	}
}
Posted
Updated 8-Nov-22 0:39am
Comments
Richard Deeming 8-Nov-22 5:06am    
Well, I'm sure all those unnecessary exclamation points in your question title will more than make up for the complete lack of detail in your question. 🤦‍♂️

Click the green "Improve question" link and edit your question. Give it a short but descriptive title. And add a clear and complete description of what you have tried, what the problem is, and where you are stuck. If you're not getting the expected output from your code, explain what output you are getting.

Java
if(arr[i]==arr[j]) {

The above code compares two references. To compare strings you need to use the equals method:
Java
if(arr[i].equals(arr[j])) {
 
Share this answer
 
Replace
Quote:
if(arr[i]==arr[j]) {
with
Java
if(arr[i].equals(arr[j])) {

That's a quirk of Java, see, for instance, Comparing Strings in Java[^].
 
Share this answer
 
v2
This is correct to compare hash codes rather than pointers to String class:

Java
if (arr[i].equals(arr[j])) ...;


Alternatively you can use HashSet<string> in java.util.* due to performance issues, as your algorithm is quadratic, it can be replaced with linear version O(n):

Java
import java.util.HashSet;

...

HashSet<String> strings = new HashSet<>();

for (int i = 0; i < arr.length; ++i) {
  if (strings.contains(arr[i])) { // check if it's already in the hash set
    System.out.println("Duplicate found: " + arr[i]);
  }

  strings.add(arr[i]); // add the string to hash set
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900