简体   繁体   中英

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.

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.

I think ReplaceFirst will replace the first occurrence.

If the selected SubString is not the first, then it will not work,

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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