在我的应用程序中我有一个EditText,它的文本是“Hello my friend,Hello”。怎么能再见第二次你好?我想将其文本更改为“Hello my friend,goodbye”。我使用了replace()语句,但用再见替换了所有的hello单词。我可以获得字母索引并用于替换吗?例如,我说程序用18到22替换字母再见。 这是我的代码:
String text = edtText.getText().toString().replace("Hello", "goodbye");
edtText.setText(text);
答案 0 :(得分:1)
试试这个:
String actualString = "Hello my friend, Hello";
String finalString = actualString.substring(0, actualString.lastIndexOf("Hello")) +
"goodbye" +
actualString.substring(actualString.lastIndexOf("Hello") + "Hello".length(), actualString.length());
答案 1 :(得分:0)
这应该有效:
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 :(得分:0)
您的解决方案。
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);
将此字符串拆分为给定正则表达式的匹配项。
此方法的工作方式就像调用带有给定表达式和limit参数为零的双参数split方法一样。因此,结尾的空字符串不包含在结果数组中。 Font
答案 3 :(得分:0)
试试这个:
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());