从特定位置删除字符串中的一个字母

huangapple go评论87阅读模式
英文:

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 &lt; str.length() - 1; i++) {
        if (str.charAt(i) == &#39;*&#39;) {
            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 = &quot;The sx*yilly dog was acting very st*tilly&quot;;
str = str.replaceAll(&quot;.\\*.&quot;,&quot;&quot;);
System.out.println(str);

Prints

The silly dog was acting very silly

huangapple
  • 本文由 发表于 2020年8月7日 08:59:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63293759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定