Home > Back-end >  capitalize first letter of string and first letter after dot
capitalize first letter of string and first letter after dot

Time:04-10

I have this string for example:

String text = 'hello. i am Gabriele. i am 21 years old!';

I would like the first letter to be capitalized and every first letter after the "." To be capitalized.

Anyone know how I can do? Thanks :)

CodePudding user response:

The first letter and all the first letters after the dot will be uppercase.

void main() {
  String text = 'hello. i am Gabriele. i am 21 years old!';
  String capitalized = capitalizeAfterDot(text);

  print(capitalized); // Hello. I am Gabriele. I am 21 years old!
}

String capitalizeAfterDot(String text) {
  final split = text.replaceAll(RegExp(r'\.\s '), ' #').split(' ');
  String result = split.reduce((a, b) {
    if (b.startsWith('#')) {
      return a   b.replaceRange(0, 2, '. '   b[1].toUpperCase());
    }
    return a   ' '   b;
  });

  return result.replaceRange(0, 1, result[0].toUpperCase());
}

CodePudding user response:

I would suggest that you iterate through the string.

Example:

Char[] arr = text.toCharArray();
Boolean toUpper = true;
arr[0] = arr[0].toUpper();
for(char c in arr)
{
 if(c.equals('.')c=c.toUpper();
}
text=c.toString();

Depending on the language you want to have this in, you have to accomodate it.

I have written this in the case you are using a pass by reference language.

  • Related