我有一个连续几个单词重复没有空格的文件,如下面的输入。我的预期输出应该如下所示。
m.mount(document.body, {
view() {
return m("table",
m("thead",
m("tr",
m("th", "Name"),
m("th", "Designation"),
m("th", "Location"),
m("th", "ID #"),
m("th", "Join Date"),
m("th", "Salary"),
)
),
m("tbody",
dataSet.map((row) => m("tr",
row.map((cell) => m("td", cell))
))
)
);
}
});
提前致谢。
答案 0 :(得分:1)
对此的修改应该有效
String input = "These are appleapple and guavaguava";
String words [] = input.split(" ");
for (String w : words) {
if (w.length() % 2 == 0) {
String firstHalf = w.substring(0, w.length() / 2 );
String secondHalf = w.substring(w.length() / 2);
if (firstHalf.equals(secondHalf)) {
System.out.println(firstHalf);
}
else {
System.out.println(w);
}
}
else {
System.out.println(w);
}
}
根据@zlakad的建议,可以通过
进行改进String input = "These are appleapple and guavaguava";
String[] words = input.split(" ");
for (String w : words) {
int half = w.length() / 2;
String firstHalf = w.substring(0, half); // split in half
String secondHalf = w.substring(half);
if (firstHalf.equals(secondHalf)) { // if equal halves then only print one
System.out.print(firstHalf + " ");
} else {
System.out.print(w + " ");
}
}
答案 1 :(得分:0)
以下是使用反向引用的选项:
String input = "These are appleapple and guavaguava";
input = input.replaceAll("\\b(\\w+)\\1\\b", "$1");
System.out.println(input);
These are apple and guava
反向引用通过匹配\b(\w+)(\1)\b
来实现。 \w+
词语将贪婪地使用最长的单词,只有当单词的其余部分与\1
匹配时才会出现匹配,这是我们刚刚匹配到该点的部分。字边界是必要的,以避免@Wombat指出的边缘情况,例如appleapples
,在没有边界的情况下,我们会错误地检测到重复的单词。
这里有一个警告,例如,如果有三个字符串一起重复,这种方法将无效。