Add separator to string at every N characters?

后端 未结 13 2293
半阙折子戏
半阙折子戏 2020-11-27 13:20

I have a string which contains binary digits. How to separate string after each 8 digit?

Suppose the string is:

string x = \"111111110000000011111111         


        
13条回答
  •  不知归路
    2020-11-27 13:42

    I did it using Pattern & Matcher as following way:

    fun addAnyCharacter(input: String, insertion: String, interval: Int): String {
      val pattern = Pattern.compile("(.{$interval})", Pattern.DOTALL)
      val matcher = pattern.matcher(input)
      return matcher.replaceAll("$1$insertion")
    }
    

    Where:

    input indicates Input string. Check results section.

    insertion indicates Insert string between those characters. For example comma (,), start(*), hash(#).

    interval indicates at which interval you want to add insertion character.

    input indicates Input string. Check results section. Check results section; here I've added insertion at every 4th character.

    Results:

    I/P: 1234XXXXXXXX5678 O/P: 1234 XXXX XXXX 5678

    I/P: 1234567812345678 O/P: 1234 5678 1234 5678

    I/P: ABCDEFGHIJKLMNOP O/P: ABCD EFGH IJKL MNOP

    Hope this helps.

提交回复
热议问题