normalizeSnakeCase method

String normalizeSnakeCase()

Transforms a string in snake case to normal case.

Example

'hello_world' -> 'hello world'.

Implementation

String normalizeSnakeCase() {
  String normalized = this;

  for (int i = 0; i < normalized.length; i += 1) {
    // Cannot access to [i - 1] when `i == 0`.
    //
    // ...foo bar...
    //       ^^
    // It's the beginning of a new word.
    if (i == 0 || normalized[i - 1] == ' ') {
      continue;
    }

    // ...foobar...
    //       ^ ^
    // Not snake case.
    if (normalized[i] != '_' || i == normalized.length - 1) {
      continue;
    }

    // ...foo_bar...
    //       ^
    // Snake case found !
    normalized = normalized.replaceRange(i, i + 1, ' ');

    // ...foo bar...
    // Result !
  }

  return normalized;
}