Java:如何将字符串中的空格和\r替换为分隔符值?

huangapple 未分类评论43阅读模式
英文:

Java: how to replace space and \r in string with delimiter value?

问题

如何用分隔符替换字符串中的空格和 \r ?

String oldDelimiter = " ";
String newDelimiter = "o";
String fileContent = "try some random %!(chars)!% ##\r" +
"or line break$@ \r" +
":(";
fileContent = fileContent.replaceAll("[" + oldDelimiter + "]+", newDelimiter);
fileContent = fileContent.replaceAll("\r", newDelimiter);


当前输出:`tryosomeo**random**o%!(chars)!%o##oorolineobreak$@oo:(`

期望输出:`tryosomeo**random**o%!(chars)!%o##oorolineobreak$@o:(`

请注意,在 `@` 符号后面的字符串末尾有额外的字母 `o`。

更新:只有在出现 `space` 或 `\r` 时才应替换为 `o`。但是,如果 `space` 和 `\r` 彼此相邻,则只替换为一个 `o` 分隔符。

<details>
<summary>英文:</summary>

How to replace space and \r in string with delimiter value?

String oldDelimiter = " ";
String newDelimiter = "o";
String fileContent = "try some random %!(chars)!% ##\r" +
"or line break$@ \r" +
":(";
fileContent = fileContent.replaceAll("[" + oldDelimiter + "]+", newDelimiter);
fileContent = fileContent.replaceAll("\r", newDelimiter);


current output: `tryosomeo**random**o%!(chars)!%o##oorolineobreak$@oo:(`

desired output: `tryosomeo**random**o%!(chars)!%o##oorolineobreak$@o:(`

Notice the extra letter `o` towards the end of the string after the `@` symbol. 

Update: it should only replace with o if there is a `space` or `\r`. However, if both `space` and `\r` and next to each other, then only replace with one `o` delimiter.

</details>


# 答案1
**得分**: -2

像安德烈亚斯所说,使用“[ \r]”来替换所有的\r和“ ”为空格。

fileContent = fileContent.replaceAll(" [ \r]+", "o");

<details>
<summary>英文:</summary>

Like Andreas said, use the &quot;[ \r]&quot; to replace all of the \r and &quot; &quot; with spaces.

    fileContent = fileContent.replaceAll(&quot;[ \r]+&quot;, &quot;o&quot;);

</details>



huangapple
  • 本文由 发表于 2020年4月10日 07:45:28
  • 转载请务必保留本文链接:https://java.coder-hub.com/61131989.html
匿名

发表评论

匿名网友

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

确定