gpt4 book ai didi

Java格式化字符串来替换特殊字符

转载 作者:行者123 更新时间:2023-12-01 18:11:54 26 4
gpt4 key购买 nike

我有这样的字符串:

String strCustom1 = "Red, Green, Blue";

我已经尝试过这个,但替换了所有 ,and

    strCustom = "Red, Green, Blue";
strCustom = strCustom.replaceAll(",", " and");

[or]

strCustom = strCustom.replace(",", " and");

像这样:

    Red and Blue and Green

但我只想替换最后一个,space+and

所以它应该看起来像这样:

    Red, Green and Blue

以同样的方式,想要格式化它:

    String strCustom2 = "Red, Green, Blue, Yellow";

因此我想得到这个:

    Red, Green, Blue and Yellow

最佳答案

你可以这样做:

strCustom = strCustom.substring(0, strCustom.lastIndexOf(",")) + " and" + strCustom.substring(strCustom.lastIndexOf(",") + 1);

关于Java格式化字符串来替换特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32344819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com