How to remove spaces that are in a string sentence

后端 未结 5 1791
-上瘾入骨i
-上瘾入骨i 2021-01-25 13:48

I am trying to write a code to remove all the leading, trailing and middle of the sentence spaces but to keep only one space between the words.

For example if the input

5条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 14:13

    You could have two arrays and two counters. Each iteration you always increase your first counter, but only increase your second when the character is not a space. A table of it would look like this.

      Char   In-Pos  Out-Pos
    
       ' '      0      0
       ' '      1      0
       ' '      2      0
       ' '      3      0
       'T'      4      0
       'h'      5      1
       'i'      6      2
       's'      7      3
       ' '      8      4
       ' '      9      5
       ' '     10      5
       ' '     11      5
       'i'     12      5
       's'     13      6
       ' '     14      7
       'm'     15      8
       'y'     16      9
       ' '     17     10
       ' '     18     11
       ' '     19     11
       ' '     20     11
       ' '     21     11
       's'     22     11
       't'     23     12
       'r'     24     13
       'i'     25     14
       'n'     26     15
       'g'     27     16
       ' '     28     17
       ' '     29     18
       ' '     30     18
       ' '     31     18
    

提交回复
热议问题