繁体   English   中英

替换字符串中子字符串的一个特定出现

[英]Replace one particular occurence of a substring in a string

我提供了在我的小型 android 项目中制作选定文本BI等基本格式选项的工具。

我需要使用选定的格式选项更改选定的文本,但发生的情况是我的函数将所有出现的选定子字符串替换为替换文本。

这是我的格式选项之一的功能:

//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));
            }
        }
    });

请我需要一个函数(内置或用户定义的),它只替换字符串中匹配子字符串的一次出现,而不是全部。

如果有人可以为我提供用于 android 中基本文本格式的现成代码(如果可用),这对我也有帮助。

我认为 ReplaceFirst 将替换第一次出现。

如果选择的 SubString 不是第一个,那么它将不起作用,

我觉得用起来比较好

text = text.substring(0,startSelection-1)+"<b>" + selectedText + "</b>"+text.substring(endSelection,text.length());

希望它会起作用:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM