removeRepeatedChar removes multiple consecutive 'char's from a string. if s == "/a//b///c////" && char == '/', it returns "/a/b/c/"
(s string, char byte)
| 153 | // removeRepeatedChar removes multiple consecutive 'char's from a string. |
| 154 | // if s == "/a//b///c////" && char == '/', it returns "/a/b/c/" |
| 155 | func removeRepeatedChar(s string, char byte) string { |
| 156 | // Check if there are any consecutive chars |
| 157 | hasRepeatedChar := false |
| 158 | for i := 1; i < len(s); i++ { |
| 159 | if s[i] == char && s[i-1] == char { |
| 160 | hasRepeatedChar = true |
| 161 | break |
| 162 | } |
| 163 | } |
| 164 | if !hasRepeatedChar { |
| 165 | return s |
| 166 | } |
| 167 | |
| 168 | // Reasonably sized buffer on stack to avoid allocations in the common case. |
| 169 | buf := make([]byte, 0, stackBufSize) |
| 170 | |
| 171 | // Invariants: |
| 172 | // reading from s; r is index of next byte to process. |
| 173 | // writing to buf; w is index of next byte to write. |
| 174 | r := 0 |
| 175 | w := 0 |
| 176 | |
| 177 | for n := len(s); r < n; { |
| 178 | if s[r] == char { |
| 179 | // Write the first char |
| 180 | bufApp(&buf, s, w, char) |
| 181 | w++ |
| 182 | r++ |
| 183 | |
| 184 | // Skip all consecutive chars |
| 185 | for r < n && s[r] == char { |
| 186 | r++ |
| 187 | } |
| 188 | } else { |
| 189 | // Copy non-char character |
| 190 | bufApp(&buf, s, w, s[r]) |
| 191 | w++ |
| 192 | r++ |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // If the original string was not modified (or only shortened at the end), |
| 197 | // return the respective substring of the original string. |
| 198 | // Otherwise, return a new string from the buffer. |
| 199 | if len(buf) == 0 { |
| 200 | return s[:w] |
| 201 | } |
| 202 | return string(buf[:w]) |
| 203 | } |