有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中用字符代码替换字符串

在Java中不知道如何用字符替换字符串。我想要一个这样的函数:

replace(string, char)

但Java中没有这样的函数

String    str = str.replace("word",  '\u0082');
String    str = str.replace("word",  (char)130);

我该怎么办


共 (3) 个答案

  1. # 1 楼答案

    你在Java中要求一个"function",你可以像这样创建一个method

    public static String replace (String text, char old, char n){
        return text.replace(old, n);
    }
    

    然后你可以随意调用method

    String a = replace("ae", 'e', '3');
    

    在这种情况下,method将返回一个String,其中a3作为值,但您不仅可以用另一个字符替换char,还可以用相同的方式用多个字符替换String

    public static String replace (String text, String old, String n){
        return text.replace(old, n);
    }
    

    然后你就这样叫它method

    String a = replace("aes", "es", "rmy");
    

    结果将是一个String,值为army

  2. # 2 楼答案

    使用长度恰好只有一个字符的字符串作为替换:

    String original = "words";
    String replaced = original.replace("word", "\u0130");
    

    replaced实例将等价于“İs”

    还要注意,从你的问题来看,'\u0130'(char)130不是相同的字符。\u语法使用十六进制,您的cast使用十进制表示法

  3. # 3 楼答案

    非常简单:

    String orginal = "asdf";
    char replacement = 'z';
    orginal = original.replace(original, replacement+"");