如何连接两个字符串并省略可能重复的单词?
How to concatenate two strings and omit possible duplicate word?
我有两个字符串,我想以一种方式连接它们,使得结果重复的 first/last 单词应该只出现一次。
示例:
String s1 = "hello world";
String s2 = "world am waiting";
String res = "hello world am waiting"; // result with only one 'world'
String s1 = "call attested";
String s2 = "attested with level A";
String res = "call attested with level A"; // result with only one 'attested'
如何连接两个字符串并省略上面看到的可能重复的单词?
您需要找到 s1
中的最后一个单词和 s2
中的第一个单词。如果这些词匹配,则在连接时省略其中一个。
为此,你可以这样写一个方法:
private static String specialConcat(String s1, String s2) {
String lastWord = s1.substring(s1.lastIndexOf(" ") + 1);
String firstWord = s2.split(" ")[0];
if (firstWord.equals(lastWord)) {
return s1 + s2.substring(lastWord.length());
} else {
return s1 + " " + s2;
}
}
以下是一些测试用例,包括边缘用例:
Assert.assertEquals("hello world am waiting",
specialConcat("hello world", "world am waiting"));
Assert.assertEquals("call attested with level A",
specialConcat("call attested", "attested with level A"));
Assert.assertEquals("", specialConcat("", ""));
Assert.assertEquals("hello", specialConcat("hello", "hello"));
Assert.assertEquals("hello world", specialConcat("hello", "world"));
Assert.assertEquals("hello world", specialConcat("hello world", "world"));
Assert.assertEquals("hello world", specialConcat("hello", "hello world"));
Assert.assertEquals("abc abcde", specialConcat("abc", "abcde"));
我有两个字符串,我想以一种方式连接它们,使得结果重复的 first/last 单词应该只出现一次。
示例:
String s1 = "hello world";
String s2 = "world am waiting";
String res = "hello world am waiting"; // result with only one 'world'
String s1 = "call attested";
String s2 = "attested with level A";
String res = "call attested with level A"; // result with only one 'attested'
如何连接两个字符串并省略上面看到的可能重复的单词?
您需要找到 s1
中的最后一个单词和 s2
中的第一个单词。如果这些词匹配,则在连接时省略其中一个。
为此,你可以这样写一个方法:
private static String specialConcat(String s1, String s2) {
String lastWord = s1.substring(s1.lastIndexOf(" ") + 1);
String firstWord = s2.split(" ")[0];
if (firstWord.equals(lastWord)) {
return s1 + s2.substring(lastWord.length());
} else {
return s1 + " " + s2;
}
}
以下是一些测试用例,包括边缘用例:
Assert.assertEquals("hello world am waiting",
specialConcat("hello world", "world am waiting"));
Assert.assertEquals("call attested with level A",
specialConcat("call attested", "attested with level A"));
Assert.assertEquals("", specialConcat("", ""));
Assert.assertEquals("hello", specialConcat("hello", "hello"));
Assert.assertEquals("hello world", specialConcat("hello", "world"));
Assert.assertEquals("hello world", specialConcat("hello world", "world"));
Assert.assertEquals("hello world", specialConcat("hello", "hello world"));
Assert.assertEquals("abc abcde", specialConcat("abc", "abcde"));