-2

Suppose we are passing a string that has several words.

Would there be a way to make the first or last letter of each word in the string to be lowercase or uppercase?

I tried the text info class but it only offers a capitalization method for every first character.

I can't really think of how it go about hard coding my own method.

  • While [this question](https://stackoverflow.com/questions/4135317/make-first-letter-of-a-string-upper-case-with-maximum-performance) is just to capitalize the first letter, the answers could be very useful to help you do your task – Steve Oct 02 '19 at 21:33
  • 1
    This is basic algorithmization. What's wrong with a `for` cycle and string indexing? – Ondrej Tucny Oct 02 '19 at 21:36
  • *How to make the last (or the first) letter of every word in a string lowercase* => **put on hold as too broad** => What?? –  Oct 02 '19 at 22:29
  • 1
    @OlivierRogier you can vote to have it reopened if you disagree! I also don't agree that this is too broad, although it would be nice if the OP posted their best effort to date so we can see what needs to be improved upon. – Rufus L Oct 02 '19 at 22:33
  • `var result = string.Concat(new CultureInfo(CultureInfo.CurrentCulture.Name).TextInfo.ToTitleCase(string.Concat(input.Reverse())).Reverse());` may work, though it will lower-case the first letter of each word at the same time. – Rufus L Oct 02 '19 at 22:35

2 Answers2

2

You can use these extensions methods to put in a static class called for example StringHelper:

    using System.Linq;
    static public string LastLetterOfWordsToLower(this string str)
    {
      if ( str == null ) return null;
      var words = str.Split(' ');
      for ( int indexWord = 0; indexWord < words.Length; indexWord++ )
      {
        string word = words[indexWord];
        if ( word != "" )
        {
          for ( int indexChar = word.Length - 1; indexChar >= 0; indexChar-- )
            if ( char.IsLetter(word[indexChar]) )
            {
              char c = char.ToLower(word[indexChar]);
              words[indexWord] = word.Substring(0, indexChar) + c;
              if ( indexChar != word.Length - 1 )
                words[indexWord] += word.Substring(indexChar + 1);
              break;
            }
        }
      }
      return string.Join(" ", words);
    }
    static public string FirstLetterOfWordsToLower(this string str)
    {
      if ( str == null ) return null;
      var words = str.Split(' ');
      for ( int indexWord = 0; indexWord < words.Length; indexWord++ )
      {
        string word = words[indexWord];
        if ( word != "" )
        {
          for ( int indexChar = 0; indexChar < word.Length; indexChar++ )
            if ( char.IsLetter(word[indexChar]) )
            {
              char c = char.ToLower(word[indexChar]);
              words[indexWord] = c + word.Substring(indexChar + 1);
              if ( indexChar != 0 )
                words[indexWord] = word.Substring(0, indexChar) + words[indexWord];
              break;
            }
        }
      }
      return string.Join(" ", words);
    }

The test:

    static public void StringHelperTest()
    {
      string[] list =
      {
        null,
        "",
        "A",
        "TEST",
        "A TEST STRING,  FOR STACK OVERFLOW!!"
      };
      foreach ( string str in list )
        Console.WriteLine(str.LastLetterOfWordsToLower());
      foreach ( string str in list )
        Console.WriteLine(str.FirstLetterOfWordsToLower());
    }

The output:



a
TESt
A TESt STRINg,  FOr STACk OVERFLOw!!


a
tEST
a tEST sTRING,  fOR sTACK oVERFLOW!!

StringBuilder can be used for performance issues.

-1

There are many ways to do this. I suggest you use the ToCharArray method to get an array of characters. Then you can loop trough the characters and determine which ones are at the first and last characters of words and change the case of the letters. This way you do only one pass and do not do any string building or concatenation.

Here are sample methods that cover both scenarios and a combined one where you set the first and last characters to lower. For upper case you just replace the ToLower call with a call to ToUpper.

private static string FirstLetterOfWordToLowercase(string stringToTransform)
{
   char[] stringCharacters = stringToTransform.ToCharArray();
   for (int charIndex = 0; charIndex < stringCharacters.Length; charIndex++)
   {
      char currentCharacter = stringCharacters[charIndex];
      if (!isWordSepparator(currentCharacter))
      {
         if (charIndex == 0 || (charIndex > 0 && isWordSepparator(stringCharacters[charIndex - 1])))
         {
            stringCharacters[charIndex] = char.ToLower(currentCharacter);
         }
      }
   }
   return new string(stringCharacters);
}

private static string LastLetterOfWordToLowercase(string stringToTransform)
{
   char[] stringCharacters = stringToTransform.ToCharArray();
   for (int charIndex = 0; charIndex < stringCharacters.Length; charIndex++)
   {
      char currentCharacter = stringCharacters[charIndex];
      if (!isWordSepparator(currentCharacter))
      {
         if (charIndex == stringCharacters.Length - 1 || isWordSepparator(stringCharacters[charIndex + 1]))
         {
            stringCharacters[charIndex] = char.ToLower(currentCharacter);
         }
      }
   }
   return new string(stringCharacters);
}

private static string FirstAndLastLetterOfWordToLowercase(string stringToTransform)
{
   char[] stringCharacters = stringToTransform.ToCharArray();
   for (int charIndex = 0; charIndex < stringCharacters.Length; charIndex++)
   {
      char currentCharacter = stringCharacters[charIndex];
      if (!isWordSepparator(currentCharacter))
      {
         if (charIndex == 0 || charIndex == stringCharacters.Length - 1 // is first or last character
            || (charIndex > 0 && isWordSepparator(stringCharacters[charIndex - 1])) // previous character was a word separator
            || isWordSepparator(stringCharacters[charIndex + 1])) // next character is a word separator
         {
            stringCharacters[charIndex] = char.ToLower(currentCharacter);
         }
      }
   }
   return new string(stringCharacters);
}

private static bool isWordSepparator(char character)
{
   return char.IsPunctuation(character) || char.IsSeparator(character);
}

Here is also a link to the .NET Fiddle where you can see it working.

Aleš Doganoc
  • 11,568
  • 24
  • 40