简体   繁体   中英

How to lowercase a string except for first character with C#

How do convert a string to lowercase except for the first character? Can this be completed with LINQ?

Thanks

If you only have one word in the string, you can use TextInfo.ToTitleCase . No need to use Linq.

As @Guffa noted:

This will convert any string to title case, so, "hello world" and "HELLO WORLD" would both be converted to "Hello World".


To achieve exectly what you asked (convert all characters to lower, except the first one), you can do the following:

string mostLower = myString.Substring(0, 1) + myString.Substring(1).ToLower();

This can be done with simple string operations:

s = s.Substring(0, 1) + s.Substring(1).ToLower();

Note that this does exactly what you asked for, ie it converts all characters to lower case except the first one that is left unchanged.

If you instead also want to change the first character to upper case, you would do:

s = s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower();

Note that this code assumes that there is at least two characters in the strings. If there is a possibility that it's shorter, you should of course test for that first.

String newString = new String(str.Select((ch, index) => (index == 0) ? ch : Char.ToLower(ch)).ToArray());

Use namespace: using System.Globalization;

...

string value = CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello");

EDIT

This code work only if its single word .For convert all character into lower except first letter check Guffa Answer.

string value = myString.Substring(0, 1) + myString.Substring(1).ToLower();

Not sure you can do it in linq here is a non-linq approach:

    public static string FirstCap(string value)
    {
        string result = String.Empty;

        if(!String.IsNullOrEmpty(value))
        {
            if(value.Length == 1)
            {
                result = value.ToUpper();
            }
            else
            {
                result = value.Substring(0,1).ToString().ToUpper() + value.Substring(1).ToLower();
            }
        }

        return result;
    }

based on guffa's example above (slightly amended). you could convert that to an extension method (please pardon the badly named method :)):

public static string UpperFirst(this string source)
{
    return source.ToLower().Remove(0, 1)
            .Insert(0, source.Substring(0, 1).ToUpper());
}

usage:

var myNewString = myOldString.UpperFirst();
// or simply referenced as myOldString.UpperFirst() where required

cheers guffa

var initialString = "Hello hOW r u?";          

var res = string.Concat(initialString..ToUpper().Substring(0, 1), initialString.ToLower().Substring(1));

You can use an extension method:

static class StringExtensions
{
    public static string ToLowerFirst(this string text)
        => !string.IsNullOrEmpty(text)
            ? $"{text.Substring(0, 1).ToLower()}{text.Substring(1)}"
            : text;
}

Unit tests as well (using FluentAssertions and Microsoft UnitTesting):

[TestClass]
public class StringExtensionsTests
{
    [TestMethod]
    public void ToLowerFirst_ShouldReturnCorrectValue()
        => "ABCD"
            .ToLowerFirst()
            .Should()
            .Be("aBCD");

    [TestMethod]
    public void ToLowerFirst_WhenStringIsEmpty_ShouldReturnCorrectValue()
        => string.Empty
            .ToLowerFirst()
            .Should()
            .Be(string.Empty);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM