如何使字符计数器排除空格和行距?

时间:2019-03-29 09:17:55

标签: android kotlin android-edittext

enter image description here

如上图所示,我在右下角有多行edittext和一个单词counter textview。

我希望计数器将根据编辑文本中输入的字符数显示数字“ 7”。因此,我要排除空格,也要排除行数(输入\ n),以计入单词计数器。

但不幸的是我得到的是“ 9”而不是“ 7”。这是我使用的代码:

class CreateEventDescriptionFragment : Fragment() {

    lateinit var fragmentView : View
    lateinit var inputEventDescriptionEditText : EditText
    lateinit var wordsCounterTextView: TextView

    lateinit var mContext : Context
    lateinit var mActivity : FragmentActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)

        mContext = context
        activity?.let { mActivity = it }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        fragmentView = inflater.inflate(R.layout.fragment_create_event_description, container, false)

        setUpViewsDeclaration()
        setUpListeners()


        return fragmentView
    }


    private fun setUpViewsDeclaration() {
        inputEventDescriptionEditText = fragmentView.findViewById(R.id.editText_event_description_input)
        wordsCounterTextView = fragmentView.findViewById(R.id.textView_words_counter_event_description)
    }


    private fun setUpListeners() {

        inputEventDescriptionEditText.addTextChangedListener(object: TextWatcher {
            override fun afterTextChanged(s: Editable?) {

                setWordsCounter(s)
                wordsCounterTextView.text = "$numberOfInputWords"

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                setWordsCounter(s)
                wordsCounterTextView.text = "$numberOfInputWords"

            }

        })

    }

    private fun setWordsCounter(words: CharSequence?) {

        val rawInputString = words.toString().trim()
        val removedEmptyLineInputString = rawInputString.replace("(?m)^[ \t]*\r?\n", "")
        val removedEmptySpaceInputString = removedEmptyLineInputString.replace(" ", "")

        numberOfInputWords = removedEmptySpaceInputString.count()

    }



}

Java没问题。这里出了什么问题?

1 个答案:

答案 0 :(得分:2)

我解决了将您的方法更改为此的问题:

private fun setWordsCounter(words: CharSequence?) {
    val rawInputString = words.toString()
        .trim()
        .replace(" ","")
        .replace("\n","")
    numberOfInputWords = rawInputString.length
}

它的作用是,首先trim()-删除所有空白,然后删除所有new lines

输出就是这个:

enter image description here