如何在edittext中只替换一个单词

dw1jzc5e  于 2021-06-30  发布在  Java
关注(0)|答案(4)|浏览(264)

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

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

8fsztsew1#

试试这个:

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());
beq87vna

beq87vna2#

试试这个:

String actualString = "Hello my friend, Hello";
String finalString = actualString.substring(0, actualString.lastIndexOf("Hello")) +
                     "goodbye" +
                     actualString.substring(actualString.lastIndexOf("Hello") + "Hello".length(), actualString.length());
klr1opcd

klr1opcd3#

这应该起作用:

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"
z6psavjg

z6psavjg4#

你的解决方案。

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方法类似。因此,结果数组中不包括尾随的空字符串。字体

相关问题