C # tries to change the first letter to uppercase, but doesn't work

I need to convert the first letter of each word that the user types in uppercase. I don’t think I am doing it right, so it won’t work, but I’m not sure where it went wrong. D: Thanks for your help! ^^

static void Main(string[] args)
    {
        Console.Write("Enter anything: ");
        string x = Console.ReadLine();

        string pattern = "^";
        Regex expression = new Regex(pattern);
        var regexp = new System.Text.RegularExpressions.Regex(pattern);

        Match result = expression.Match(x);
        Console.WriteLine(x);

        foreach(var match in x)
        {
            Console.Write(match);
        }
        Console.WriteLine();
    }
+4
source share
6 answers

If your exercise is not a regular expression, there are built-in utilities to perform your tasks:

System.Globalization.TextInfo ti = System.Globalization.CultureInfo.CurrentCulture.TextInfo;
string titleString = ti.ToTitleCase("this string will be title cased");

Console.WriteLine(titleString);

Print

This line will be overlaid in the title.

If you're working with regex, see StackOverflow: Sublime Text: Regex previous answer for converting to uppercase to header?

+6
source

, Regex "^" . , Regex, . "[A-Za-Z]".

, . , # ( ), , , , . . , .

+1
string pattern = "(?:^|(?<= ))(.)"

^ . uppercase letters, $1. . .

https://regex101.com/r/uE3cC4/29

+1

,

public static string CapsFirstLetter(string inputValue)
    {
        char[] values = new char[inputValue.Length];
        int count = 0;
        foreach (char f in inputValue){
            if (count == 0){
                values[count] = Convert.ToChar(f.ToString().ToUpper());
            }
            else{
                values[count] = f;
            }
            count++;
        }
        return new string(values);
    }
0

:

string input = "this string will be title cased, even if there are.cases.like.that";
string output = Regex.Replace(input, @"(?<!\w)\w", m => m.Value.ToUpper());
0

, .

PHP , ucfirst. #

public static string UcFirst(this string s)
{
    var stringArr = s.ToCharArray(0, s.Length);
    var char1ToUpper = char.Parse(stringArr[0]
        .ToString()
        .ToUpper());

    stringArr[0] = char1ToUpper;

    return string.Join("", stringArr);
}

:

[Test]
public void UcFirst()
{
    string s = "john";
    s = s.UcFirst();
    Assert.AreEqual("John", s);
}

, UcFirst .

Google #, , .

0

All Articles