英文:
Removing a letter from a string at a specific position
问题
我正在尝试定位字符串中的 * 并删除它以及它前面和后面的字符。
例如,字符串 st*tilly 将输出 silly。
到目前为止,这是我拥有的代码:
public static String starOut(String str) {
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '*') {
sb.deleteCharAt(i);
if (i > 0) {
sb.deleteCharAt(i - 1);
i--;
}
if (i < sb.length() && sb.charAt(i) == '*') {
sb.deleteCharAt(i);
i--;
}
}
}
return sb.toString();
}
英文:
I am trying to locate the * in a string and remove it and the characters in front and before it.
for example the string st*tilly will output silly
this is what I have so far
public static String starOut(String str) {
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) == '*') {
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(i);
sb.deleteCharAt(i+1);
sb.deleteCharAt(i-1);
sb.toString();
}
}
return sb;
}
答案1
得分: 1
你可以这样做。它使用了正则表达式
.
匹配任何字符。\\*
匹配一个星号。它必须被转义,因为在正则表达式中它有特殊的含义。
String str = "The sx*yilly dog was acting very st*tilly";
str = str.replaceAll(".*\\*.*","");
System.out.println(str);
输出
The silly dog was acting very silly
英文:
You could do it like this. It uses a regular expression
.
matches any character.\\*
matches an asterisk. It has to be escaped because by itself it has a special meaning in regular expressions.
String str = "The sx*yilly dog was acting very st*tilly";
str = str.replaceAll(".\\*.","");
System.out.println(str);
Prints
The silly dog was acting very silly
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论