簡體   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