我试图解决一些字符串任务,但我有一些问题。我不明白我如何搜索2个不同的字符,如果1个字符在这2个字符之间,如何删除。
我的任务是:
在字符串中查找像"zip“和"zap”这样的模式-- length-3,以“z”开头,以“p”结束。返回一个字符串,其中对于所有这样的单词,中间的字母都没有了,因此"zipXzap“将生成"zpXzp”。我的代码是:
public String zipZap(String str) {
char z = 'z';
char p = 'p';
for (int i = str.indexOf('z', 0); i != -1; i = str.indexOf('z', 1)) {
for (int j = str.indexOf('p', 0); i != -1; i = str.indexOf('p', 1)) {
if (p = i + 2) {
str = str.replace(i + 1, " ");
}
}
}
return str;
} 发布于 2018-12-10 22:39:01
试试这个:
public String zipZap(String str) {
return str.replaceAll("z[a-z]p", "zp");
}https://stackoverflow.com/questions/53707786
复制相似问题