2014-02-13 80 views
-1

如何让字符串小写字母的第一个字符?字符串小写字母的第一个字符 - C#

例如:ConfigService

,我需要它是这样的:configService

+0

您是否检查了这一点? http://stackoverflow.com/questions/3565015/bestpractice-transform-first-character-of-a-string-into-lower-case – Niklas

+0

http://stackoverflow.com/questions/4135317/make-first-letter- of-a-string-upper-case改为'ToUpper'将其改为'ToLower'。 – Random

+3

注意:任何“第一个字符”相关的事情在讨论任何非简单unicode之外的事情时都会非常危险。结合变音符号,共轭对和从右到左都会导致问题 –

回答

6

这将工作:

string s = "ConfigService"; 
      if (s != string.Empty && char.IsUpper(s[0])) 
      { 
       s= char.ToLower(s[0]) + s.Substring(1); 
      } 
      Console.WriteLine(s); 
+1

不要忘记检查空字符串。 – nima

+0

只包含一个字符的字符串。 – Crono

+0

@nima我编辑过它 –

7

方式一:

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

对于它的价值,扩展方法:

public static string ToLowerFirstChar(this string input) 
{ 
    string newString = input; 
    if (!String.IsNullOrEmpty(newString) && Char.IsUpper(newString[0])) 
     newString = Char.ToLower(newString[0]) + newString.Substring(1); 
    return newString; 
} 

用法:

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

这对DBCS是否正常工作? –

+2

@ThorstenDittmar .NET有Unicode字符串。而char代表UTF-16字符 –

+1

@SergeyBerezovskiy正确。然而,同样的问题适用于代理对,这将不会被正确处理(并且只是在一般情况下没有正确处理,在我见过的大多数代码中)。 – hvd

1

你可以试试这个:

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

另外,使用'Substring'方法来获取第一个字符似乎有点超过顶部:) – Tarec

1

我只想做到这一点:

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

简单,能够完成任务。

编辑:

看起来this thread有同样的想法。 :)

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

使用此功能:

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); 
} 

请注意,如果需要对其他语言的支持,进一步超载将是必要的。

1

这可以帮助你,改变第一个字符下,如果它是上,还检查null或空,只有空白字符串:

string str = "ConfigService"; 
string strResult = !string.IsNullOrWhiteSpace(str) && char.IsUpper(str, 0) ? str.Replace(str[0],char.ToLower(str[0])) : str; 
2
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; 
    } 

希望这将帮助你!在这里我提出了两种方法,以任何字符串作为参数,并根据您将使用的方法将字符串以第一个字母大写或小写字符返回

相关问题