有 Java 编程相关的问题?

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

java如何在EditText中只替换一个单词

在我的应用程序中,我有一个EditText,它的文本是“你好,我的朋友,你好”。我怎样才能用再见代替第二声你好?我想把它的文字改成“你好,我的朋友,再见”。我使用replace()语句,但将所有hello单词替换为再见。我可以得到字母索引并用于替换吗?例如,我对一个用再见代替18到22个字母的程序说。 这是我的代码:

String text = edtText.getText().toString().replace("Hello", "goodbye");
edtText.setText(text);

共 (4) 个答案

  1. # 1 楼答案

    这应该起作用:

    public static String replace(String phrase, String before, String after, int index) {
        String[] splittedPhrase = phrase.split(" ");
        String output = "";
        for (int i = 0, j = 0; i < splittedPhrase.length; i++) {
            if (i != 0)
                output += " ";
            if (splittedPhrase[i].equals(before) && index == j++)
                output += after;
            else
                output += splittedPhrase[i];
        }
        return output;
    }
    

    或者,简而言之:

    public static String replace(String phrase, String before, String after, int index) {
        int i = 0;
        String output = "";
        for (String s : phrase.split(" "))
            output += ((s.equals(before) && index == i++) ? after : s) + " ";
        return output.substring(0, output.length() - 1);
    }
    

    然后,简单地说:

    public static void main(String args[]) {
        System.out.println(replace("hello world, hello", "hello", "goodbye", 0));
        System.out.println(replace("hello world, hello", "hello", "goodbye", 1));
        System.out.println(replace("hello world, hello", "hello", "goodbye", 2));
    }
    

    打印出:

    "goodbye world, hello"
    "hello world, goodbye"
    "hello world, hello"
    
  2. # 2 楼答案

    试试这个:

    string hello = "hello";
    int start =0;
    int end =0;
    String text = edtText.getText().toString();
    String replacement = "replacement";
    start=text.indexOf(hello, str.indexOf(hello) + 1);
    end=start+hello.lenght();
    
    StringBuilder s = new StringBuilder();
     s.append(text.substring(0, start)));
     s.append(replacement);
     s.append(text.substring(end);
    edtText.setText(s.toString());
    
  3. # 3 楼答案

    试试这个:

    String actualString = "Hello my friend, Hello";
    String finalString = actualString.substring(0, actualString.lastIndexOf("Hello")) +
                         "goodbye" +
                         actualString.substring(actualString.lastIndexOf("Hello") + "Hello".length(), actualString.length());
    
  4. # 4 楼答案

    你的解决方案

     et = (EditText) findViewById(R.id.editText);
     String text = "Hello my friend , Hello";
     et.setText(text);
     String[] txt = text.split("Hello");
     for (int x = 0 ; x < txt.length ; x++)
         System.out.println(txt[x]); //for cast
     text = "goodbye" + txt[0] + txt[1] + "goodbye";
     et.setText(text);
    

    围绕给定正则表达式的匹配项拆分此字符串

    该方法的工作原理类似于使用给定表达式和零限制参数调用双参数split方法。因此,结果数组中不包括尾随的空字符串。 Font