[英]How to avoid string repetition
I have two different string String A="example"; String B="example";
我有两个不同的string String A="example"; String B="example";
string String A="example"; String B="example";
if concat both the string i am getting examplexample.
如果同时连接两个字符串,我将得到examplexample.
Is there any possibility to avoid repetition of string with same name..?? 有没有可能避免重复相同名称的字符串。
How about this ? 这个怎么样 ?
if(!a.equals(b)){// or if needed use contains() , equalIgnoreCase() depending on your need
//concat
}
The Strings are not different , the same String object is assigned to two different variables ("two pointers to the same memory address"). 字符串相同 , 相同的 String对象被分配给两个不同的变量(“指向相同内存地址的两个指针”)。
Consider dumping all strings to a Set
before concatenating, this avoids duplicates in the concatenated sequence: 考虑在连接之前将所有字符串转储到Set
,这样可以避免在连接序列中出现重复项:
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();
Just create a Set (It has mathematics set behaviour, it won't accept the duplicate objects) 只需创建一个Set(它具有数学的set行为,它将不接受重复的对象)
Set<String> strings = new HashSet<String>();
//Fill this set with all the String objects //使用所有String对象填充此集合
strings.add(A)
Strings.add(B)
//Now iterate this set and create a String Object //现在迭代此集合并创建一个String对象
StringBuilder resultBuilder = new StringBuilder();
for(String string:Strings){
resultBuilder.append(string);
}
return resultBuilder.toString()
` `
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 "";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.