0

我有一个字符串

String s = "#@#:g#@# hello #@#:(#@# How are You";

#@#:g#@# 是表情符号的代码。类似下一个#@#:(#@# 是另一个代码。

现在我的字符串有几个以#@# 开头并以#@# 结尾的代码。现在我需要用另一个字符串“(情绪)”替换所有以#@# 开头并以#@# 结尾的子字符串。

Input String = "#@#:g#@# hello  #@#:(#@# How are you";
Output String  = "(emotions) hello (emotions) How are You".

我试过这段代码

System.out.println("Original String is = "+s);
    if(s.contains("#@#"))
    {
        //int startIndex = s.substring(beginIndex, endIndex)
        int index = s.indexOf("#@#");
        while (index >= 0) {
            System.out.println("index is == "+index);
            arr.add(index);
            index = s.indexOf("#@#", index + 1);
        }

        for(int i = 0 ; i<arr.size() ; i=i+2)
        {
            int startIndex = arr.get(i);
            int secondIndex = arr.get(i+1);
            System.out.println("StartIndex is == "+startIndex);
            System.out.println("SecondIndex is == "+secondIndex);

            String s1 = s.substring(startIndex,secondIndex+3);

            System.out.println("String to be replaced is == "+s1.toString());
            s.replace(s1, "(emotions)");             //\"(emotions)\"
            System.out.println("String  == "+s.toString());
        }
    }

    System.out.println("Final String is == "+s.toString());
}

请帮我。

4

6 回答 6

4

使用String.replaceAll

String input = "#@#:g#@# hello  #@#:(#@# How are you";
String output = input.replaceAll("#@#.*?#@#", "(emotions)");
System.out.println(output); // (emotions) hello  (emotions) How are you

传递给的第一个参数replaceAll是“#@#”的正则表达式,后跟任何字符,后跟“#@#”。

于 2013-10-22T10:08:11.273 回答
0

尝试String.replace

String s = "#@#:g#@# hello #@#:(#@# How are You";
String output = s.replace("#@#", " ");
System.out.println(output);

编辑

public String replace(String s){
    if(s.contains("#@#:g#@#")){
       s.replace("#@#:g#@#", "requiredString1");
    }
    if(s.contains("#@#:)#@#")){
       s.replace("#@#:)#@#", "requiredString2");
    }   

//add other required patterns here
       return s;
}
于 2013-10-22T10:04:15.747 回答
0
  • 首先,您必须将空格拆分为一个数组。
  • 创建一个新String的作为输出。
  • 然后,遍历数组和 if item(i).contains("#@#")->output+="(emotions) " else output += item(i)"#@#"

希望能帮助到你

于 2013-10-22T10:07:17.840 回答
0

使用拆分方法。

String line = "#@#:g#@# hello #@#:(#@# How are You";
String tokens[] = line.split("#@#");
for(String token: tokens){
    System.out.println(token);
    if(token.equals(":g")){
         // replace with emoticon
    }
    ....
}
于 2013-10-22T10:19:21.130 回答
0

试试这样:--

String s = "#@#:g#@# hello #@#:(#@# How are You";
        String s1=s.replace("#@#:g#@#", "(emotions)");
        String s2=s1.replace("#@#:(#@#", "(emotions)");
        System.out.println(s2);
于 2013-10-22T10:23:59.110 回答
0

这会将“#@#{xx}#@#”替换为“(情绪)”。{xx} 严格来说是任意 2 个字符。

"#@#:g#@# hello  #@#:(#@# How are you".replaceAll("#@#.{2}#@#", "(emotions)");

Input : #@#:g#@# hello  #@#:(#@# How are you
Output: (emotions) hello  (emotions) How are you
于 2013-10-22T10:34:55.993 回答