有人可以帮我吗?我不明白问题出在哪里......
我需要检查一个字符串是否有超过 1 个字符,如“a”,如果是,我需要将所有“a”替换为空白,但我仍然只想要一个“a”。
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
应用程序在进入 while 循环时停止工作。有什么建议吗?非常感谢!
最佳答案
如果您想替换字符串中除最后一个之外的每个a
,那么您可以尝试以下正则表达式选项:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
编辑:
如果您确实想要删除除最后一个之外的所有a
,请使用以下命令:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
关于java - 替换字符并仅保留其中一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49683582/