简体   繁体   English

如何用C#小写除第一个字符以外的字符串

[英]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? 这可以用LINQ完成吗?

Thanks 谢谢

If you only have one word in the string, you can use TextInfo.ToTitleCase . 如果字符串中只有一个单词,则可以使用TextInfo.ToTitleCase No need to use Linq. 无需使用Linq。

As @Guffa noted: 正如@Guffa所说:

This will convert any string to title case, so, "hello world" and "HELLO WORLD" would both be converted to "Hello World". 这会将任何字符串转换为标题大小写,因此,“hello world”和“HELLO WORLD”都将转换为“Hello World”。


To achieve exectly what you asked (convert all characters to lower, except the first one), you can do the following: 为了实现exectly你问(转换所有字符时,除了第一个),你可以做到以下几点:

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; 使用命名空间: 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. 此代码仅在其单个单词时起作用。对于将所有字符转换为较低的除了第一个字母检查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: 不确定你能在linq中做到这里是一个非linq方法:

    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). 基于上面的guffa示例(稍作修改)。 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 欢呼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): 单元测试(使用FluentAssertions和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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#:如何获取字符串的第一个字符? - C#: how to get first character of a string? c# - 正则表达式从字符串中删除元音,除了第一个和最后一个字符 - c# - regex to remove vowels from string except first and last character 如何在C#中删除字符串的第一个和最后一个字符? - How to remove first and last character of a string in C#? 如何检查字符串的第一个字符,如果是字母,C# 中的任何字母 - How to check first character of a string if a letter, any letter in C# 如何使用 C# 将每个单词的第一个字符或整个字符串的第一个字符大写? - How to capitalize the first character of each word, or the first character of a whole string, with C#? C#拆分第一个字符出现的字符串 - C# split string of first character occurrence 删除字符串C#的第一个和最后一个字符 - Removing the first and last character of a string C# 如何使用C#替换字符串中的单词(首次出现的除外) - How do I replace word in string except first occurrence using c# 如何使用C#在字符串中的第一个数字值之后用指定的字符替换空格/字符? - How to replace space/character with specified character after first numeric value in string using C#? 如何提取第一个字符和之后的数字,直到在字符串中找到字符 (az) - C# 2.0 - How to extract first character and numbers after that until find a character (a-z) in a string - C# 2.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM