0

I have two different string String A="example"; String B="example"; if concat both the string i am getting examplexample. Is there any possibility to avoid repetition of string with same name..??

1
  • It's unclear what you're trying to do... why are you concatenating the strings if you don't want them concatenated? Could you give more sample inputs/outputs? Commented May 17, 2011 at 6:01

4 Answers 4

3

How about this ?

if(!a.equals(b)){// or if needed use contains() , equalIgnoreCase() depending on your need
 //concat
}
Sign up to request clarification or add additional context in comments.

Comments

1

The Strings are not different, the same String object is assigned to two different variables ("two pointers to the same memory address").

Consider dumping all strings to a Set before concatenating, this avoids duplicates in the concatenated sequence:

Set<String> strings = new HashSet<String>();
StringBuilder resultBuilder = new StringBuilder();
for (String s:getAllStrings()) {  // some magic to get all your strings
   if (strings.contains(s))
       continue;                  // has been added already
   resultBuilder.append(s);       // concatenate
   strings.add(s);                // put string to set
}
String result = resultBuilder.toString();

Comments

1

You can. Try something like this

private String concatStringExample1(String firstString, String secondString) {
            if(firstString.equalsIgnoreCase(secondString)) { // String matched
                 return firstString;  // or return secondString
            } else { // Not matched
                return firstString.concat(secondString); 
            }
        }

or

private String concatStringExample2(String firstString, String secondString) {
            if(firstString != null && firstString != null ) {
                if(firstString.toLowerCase().indexOf(secondString.toLowerCase()) >= 0)
                    return firstString;
                else if(secondString.toLowerCase().indexOf(firstString.toLowerCase()) >= 0)
                    return secondString;
                else
                    return firstString.concat(secondString);
            } else {
                return "";
            }
        }

Comments

1

Just create a Set (It has mathematics set behaviour, it won't accept the duplicate objects)

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

//Fill this set with all the String objects

strings.add(A)
Strings.add(B)

//Now iterate this set and create a String Object

StringBuilder resultBuilder = new StringBuilder();

for(String string:Strings){
resultBuilder.append(string);
}
return resultBuilder.toString()

`

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.