Problem:
Given two strings, append them together (known as "concatenation") and return the result. However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".
conCat("abc", "cat") → "abcat"
conCat("dog", "cat") → "dogcat"
conCat("abc", "") → "abc"
Solution:
public String conCat(String a, String b) { if (a.length() == 0 || b.length() == 0) return a+b; if ((a.substring(a.length() - 1, a.length())).equals(b.substring(0,1))) return a + b.substring(1,b.length()); else return a+b; }
Wouldn's this be better?
ReplyDeletepublic String conCat(String a, String b) {
if (a.length()>0 && b.length()>0 && b.charAt(0)==a.charAt(a.length()-1))
b=b.substring(1);
return a+b;
}
public String conCat(String a, String b) {
ReplyDeleteif(!(a.length()==0||b.length()==0)&&a.substring(a.length()-1).equals(b.substring(0,1))){
return a+b.substring(1);
}else return a+b;
I love you so much
DeleteThis right here
Deletepublic String conCat(String a, String b) {
ReplyDeletereturn a.length()!=0&&b.length()!=0&&a.substring(a.length()-1).equals(b.substring(0,1))?
a+b.substring(1,b.length()):a+b;
}
Does anyone know why comparing the individual characters from each string doesn't work? Like saying something like:
ReplyDeleteif(a.charAt(0) == b.charAt(0))
Why doesn't that work? I don't understand the need to use substring when we only care about two individual characters. Any help is appreciated.
I meant to say a.charAt(a.length()-1) == b.charAt(0)
Deletedid u get any answer
DeleteNever mind, I got it to work like that.
ReplyDeleteCould you do this in def?
ReplyDeletedef conCat (a, b):
Same issue:)
Deleterequired in python any on help me plz
ReplyDeletepublic String conCat(String a, String b) {
ReplyDeleteif (b.length() == 0) return a;
if (a.endsWith(b.substring(0, 1))) return a + b.substring(1);
return a + b;
}
public String conCat(String a, String b) {
ReplyDeleteif(a.length() == 0 || b.length() == 0){
return a + b;
}
if(a.endsWith(b.substring(0,1))){
return a + b.substring(1);
}
return a + b;
}
public String conCat(String a, String b)
ReplyDelete{
String data = "";
if(a.length() > 1)
data += a;
if(b.length() > 1)
{
if(data.length()>0 && data.charAt(data.length()-1) == b.charAt(0))
data += b.substring(1);
else
data += b;
}
return data;
}
if(a.length()==0)
ReplyDeletereturn b;
else if(b.length()==0)
return a;
else if(a.charAt((a.length()-1))==b.charAt(0))
return a.substring(0,a.length()-1)+b.substring(0,b.length());
else
return a.substring(0,a.length())+b.substring(0,b.length());
In JavaScript we can solve it, like this:
ReplyDeletefunction conCat(a, b){
if(a[a.length - 1] == b[0]) {
b = b.substring(1);
return a + b
} else {
return a + b
}
}
public String conCat(String a, String b) {
ReplyDeleteString res="";
if((a.length()==0 || b.length()==0) ||
a.length()>1 && b.length()>1 &&
a.charAt(a.length()-1)!=b.charAt(0)){
return res=a+b;
}else if(a.charAt(a.length()-1)==b.charAt(0)){
res = res+a+b.substring(1);
}
return res;
}