[英]Replace one particular occurence of a substring in a string
I am providing facilites to make selected text B and I and etc basic formatting options in my small android project.我提供了在我的小型 android 项目中制作选定文本B和I等基本格式选项的工具。
I need to change selected text with the chosen formatting option but what happens is that my function replaces all of the occurrences of selected substring with replacement text.我需要使用选定的格式选项更改选定的文本,但发生的情况是我的函数将所有出现的选定子字符串替换为替换文本。
Here's my function for one of the formatting options :这是我的格式选项之一的功能:
//Make selectedText bold
bold.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Gets selection text's start and end position
int startSelection = etText.getSelectionStart();
int endSelection = etText.getSelectionEnd();
text = String.valueOf((new SpannableString(etText.getText())));
/*This is just to make sure selected string does not end up with
negative length */
if (startSelection > endSelection) {
startSelection = etText.getSelectionEnd();
endSelection = etText.getSelectionStart();
}
//Stores the text selected by user in a string.
String selectedText = etText.getText().toString().substring(startSelection, endSelection);
if (!selectedText.isEmpty()) {
/*Here selectedText is replaced with formattedText using replace function which maybe causing the replacement of all occurrences in text.*/
text = text.replace(selectedText, "<b>" + selectedText + "</b>");
etText.setText(Html.fromHtml(text));
}
}
});
Please i need a function (Inbuilt or User-defined) which replaces ONLY ONE occurrence of matching substring in a string instead of all.请我需要一个函数(内置或用户定义的),它只替换字符串中匹配子字符串的一次出现,而不是全部。
It will be also helpful to me if one can provide me ready code for basic text formatting in android if available.如果有人可以为我提供用于 android 中基本文本格式的现成代码(如果可用),这对我也有帮助。
I think ReplaceFirst will replace the first occurrence.
我认为 ReplaceFirst 将替换第一次出现。
If the selected SubString is not the first, then it will not work,如果选择的 SubString 不是第一个,那么它将不起作用,
I think it is better to use,我觉得用起来比较好
text = text.substring(0,startSelection-1)+"<b>" + selectedText + "</b>"+text.substring(endSelection,text.length());
Hope it will work:)希望它会起作用:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.