Make all the first letters uppercase except for words with at max 3 characters

133 Views Asked by At

I have a text file that the users can edit with many strings, I would like to have all the first letters uppercase except for words with <= 3 characters that must be all uppercase.

using LINQPAD I read the txt file like this
var textFile = File.ReadAllText(@"C:\...\...\...\...\uppercase.txt");

example of a file :
THE PEN IS ON THE TABLE
The cat is UNder ThE Table
The ChiLDreN Are ON The trampoline

Wanted output:
THE PEN IS ON THE Table
THE CAT IS Under THE Table
THE Children ARE ON THE Trampoline

3

There are 3 best solutions below

0
Tim Schmelter On

You can use this approach:

var newWords = textFile.Split(' ')
    .Select(w => w.Length <= 3 ? w.ToUpper() : char.ToUpper(w[0]) + w[1..].ToLower());
textFile = String.Join(" ", newWords);
0
Dmitry Bychenko On

Given text:

string text = 
   @"THE PEN IS ON THE TABLE
     The cat is UNder ThE Table
     The ChiLDreN Are ON The trampoline";

We can use regular expressions to do replacements:

using System.Text.RegularExpressions;
using System.Globalization;

...

string result = Regex.Replace(text,
  @"\p{L}+",
    match => match.Value.Length > 3
      ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(match.Value)
      : match.Value.ToUpper());

Here I treat word as a non empty sequence of letters \p{L}+. Please, note, that regular expressions unlike split respect punctuations:

"The cat! Not a dog" -> "THE CAT! NOT A DOG"

Fiddle

0
Hr.Panahi On

Here is how I did it:

string txt = "THE PEN IS ON THE TABLE\nThe cat is UNder ThE Table\nThe ChiLDreN Are ON The trampoline";
var lines = txt.Split('\n');

I split txt with \n first, then:

foreach (var line in lines)
{
    var words = line.Split(' ');
    foreach (var word in words)
    {
        if (word.Length <= 3)
        {
            Console.Write(word.ToUpper() + " ");
        }
        else
        {
            Console.Write(word.Substring(0, 1).ToUpper() + word.Substring(1).ToLower() + " ");
        }
    }
    Console.WriteLine();
}

Then I used a foreach loop to iterate through the lines array to get each element in it and split it with Split(' ').

Then I used another foreach loop to iterate through each element in words to get each word in it and do the capitalization and printing.

I am new to C# and just wanted to help since I tried this approach and it worked.