hide-place / StringsAdd

MIT License
0 stars 0 forks source link

Enhanced Version Of `titleCase` #1

Open abdelhakim-sahifa opened 2 months ago

abdelhakim-sahifa commented 2 months ago

Here's an enhanced version of the titleCase function with additional features:

  1. Excludes short words from capitalization: Words like "and", "or", "the" won't be capitalized unless they're the first or last word.
  2. Handles acronyms: Words in all caps will remain in all caps.
  3. Deals with hyphenated words: Both parts of hyphenated words will be capitalized.
String titleCase(String text) {
  final List<String> excludeWords = ['and', 'or', 'the', 'to', 'of', 'for', 'in', 'on', 'at', 'by', 'with', 'as'];
  final List<String> words = text.trim().split(RegExp(r'\s+'));

  String capitalize(String word) {
    if (word.length <= 2 || word.toUpperCase() == word) return word;
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  }

  for (int i = 0; i < words.length; i++) {
    if (words[i].contains('-')) {
      words[i] = words[i]
          .split('-')
          .map((part) => capitalize(part))
          .join('-');
    } else if (i == 0 || i == words.length - 1 || !excludeWords.contains(words[i].toLowerCase())) {
      words[i] = capitalize(words[i]);
    } else {
      words[i] = words[i].toLowerCase();
    }
  }

  return words.join(' ');
}

This enhanced version of titleCase takes care of more specific capitalization rules, making the output more refined and accurate for a variety of text inputs.

abdelhakim-sahifa commented 2 months ago

Function Definition

String titleCase(String text) {

List of Words to Exclude

  final List<String> excludeWords = ['and', 'or', 'the', 'to', 'of', 'for', 'in', 'on', 'at', 'by', 'with', 'as'];

Splitting the Text into Words

  final List<String> words = text.trim().split(RegExp(r'\s+'));

Capitalize Function

  String capitalize(String word) {
    if (word.length <= 2 || word.toUpperCase() == word) return word;
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  }

Loop Through Words and Capitalize as Needed

  for (int i = 0; i < words.length; i++) {
    if (words[i].contains('-')) {
      words[i] = words[i]
          .split('-')
          .map((part) => capitalize(part))
          .join('-');
    } else if (i == 0 || i == words.length - 1 || !excludeWords.contains(words[i].toLowerCase())) {
      words[i] = capitalize(words[i]);
    } else {
      words[i] = words[i].toLowerCase();
    }
  }

Joining Words Back into a String

  return words.join(' ');
}

Summary

This function converts a given string into title case while handling special cases such as hyphenated words and small words that should not be capitalized unless they are the first or last word in the string.