Pregunta

How can I make the first character of a string lowercase?

For example: ConfigService

And I need it to be like this: configService

¿Fue útil?

Solución

This will work:

public static string? FirstCharToLowerCase(this string? str)
{
    if ( !string.IsNullOrEmpty(str) && char.IsUpper(str[0]))
        return str.Length == 1 ? char.ToLower(str[0]).ToString() : char.ToLower(str[0]) + str[1..];

    return str;
}

(This code arranged as "C# Extension method")

Usage:

myString = myString.FirstCharToLowerCase();

Otros consejos

One way:

string newString = oldString;
if (!String.IsNullOrEmpty(newString))
    newString = Char.ToLower(newString[0]) + newString.Substring(1);

For what it's worth, an extension method:

public static string ToLowerFirstChar(this string input)
{
    if(string.IsNullOrEmpty(input))
        return input;

    return char.ToLower(input[0]) + input.Substring(1);
}

Usage:

string newString = "ConfigService".ToLowerFirstChar(); // configService

You could try this:

lower = source.Substring(0, 1).ToLower() + source.Substring(1);
    string FirstLower(string s)
    {
        if(string.IsNullOrEmpty(s))
            return s;
        return s[0].ToString().ToLower() + s.Substring(1);
    }

Use this function:

public string GetStringWithFirstCharLowerCase(string value)
{
    if (value == null) throw new ArgumentNullException("value")
    if (String.IsNullOrWhiteSpace(value)) return value;

    char firstChar = Char.ToLowerInvariant(value[0]);

    if (value.Length == 1) return firstChar;

    return firstChar + value.Substring(1);
}

Please note that further overloading will be necessary if support for other languages is required.

    public static string Upper_To_Lower(string text)
    {
        if (Char.IsUpper(text[0]) == true) { text = text.Replace(text[0], char.ToLower(text[0])); return text; }

        return text;
    }

    public static string Lower_To_Upper(string text)
    {
        if (Char.IsLower(text[0]) == true) { text = text.Replace(text[0], char.ToUpper(text[0])); return text; }

        return text;
    }

Hope this will help you ! here i made two methods taking as parameter any string and return the string with the first letter uppercase or lowercase according to the method you will use

string test = "ConfigService";
string result = test.Substring(0, 1).ToLower() + test.Substring(1);

I would simply do this:

Char.ToLowerInvariant(yourstring[0]) + yourstring.Substring(1)

Simple and gets the job done.

EDIT:

Looks like this thread had the same idea. :)

This can help you,changes first character to lower if it is upper and also checks for null or empty and only whitespace string:

string str = "ConfigService";
string strResult = !string.IsNullOrWhiteSpace(str) && char.IsUpper(str, 0) ? str.Replace(str[0],char.ToLower(str[0])) : str;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top