java - 从字符串中删除指定字符

标签 java string

<分区>

我对使用 String.replaceAll 函数很感兴趣,该函数允许我删除字符串的特定序列。

  1. String.replaceAll 的功能是否替换给定的字符串序列的第一次出现,以及替换?我的假设是肯定的。

  2. 要替换特定的子字符串,我将如何替换提供的字符串中的字符?

    String sentence = "@red@@blue@@green@Hello@reset@";
    

    我要删除的子字符串是从 @ 到另一个 @,在这种情况下,在运行 String.replace

    String.replaceAll("@**PATTERN HERE SO NAME WON"T MATTER**@", "");
    

编辑 看到 replace 和 replaceAll 使得两者之间存在差异,因为它们是使用正则表达式的。 我关心的是删除第一次出现的给定表达式,即

的原始字符串
String sentence = "@red@@blue@@green@Hello@reset@";

必须运行 4 次才能将“Hello”作为字符串的剩余成员。

例子: 运行 1 - replaceFirstOccurence("@regex@", "");

System.out.println(sentence); --> "@blue@@green@Hello@reset@"

运行 2 - replaceFirstOccurence("@regex@", "");

System.out.println(sentence); --> "@green@Hello@reset@"

运行 3 - replaceFirstOccurence("@regex@", "");

System.out.println(sentence); --> "Hello@reset@"

运行 4 - replaceFirstOccurence("@regex@", "");

System.out.println(sentence); --> "Hello"

最佳答案

使用String的标准方法replaceAll(String regular Expression, String replacement)

例如: "@some chars@".replaceAll("@[^@]*@", "@@");

关于java - 从字符串中删除指定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608684/

相关文章:

java - 如何将 fragment 制作为应用程序启动 Activity

java - 如何将 org. Threeten.bp 库中的 OffsetDateTime 插入 db Oracle 列

java - JUnit4 使用测试套件运行特定包中的所有测试

java - 如何使用按键绑定(bind)而不是按键监听器

具有未定义输入的 C 中的凯撒加密

c# - arduino 设备发送的数据中缺少 "NewLine"个字符

java - 合适的数据结构

c - C 语言中使用指针处理字符串

python - 在 Python 中从文件名中提取文件扩展名的方法是什么?

c - 如何进行不区分大小写的字符串比较?