我正在尝试将位于第一个空格之后的字符串中的第一个字母大写:
string name = "Jeffrey steinberg";
我正在尝试将 steinberg 中的 S 大写。我不知道该怎么做。我尝试过使用 toupper 函数,但不知道如何引用字符“s”,因为 c# 字符串不是 c 中的数组。
您可以为此使用 TitleCase:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase("Jeffrey steinberg"));
}
}
string name = "Jeffrey steinberg";
TextInfo myTI = new CultureInfo("en-US",false).TextInfo;
myTI.ToTitleCase(name)
某些文化不会使 ToTitleCase 起作用,因此最好使用 en-us 来制作标题大小写。
如果要替换字符串中的单个字符,则不能对该字符串执行替换字符数组中的元素的操作。NET 中的字符串是不可变的。这意味着您无法更改它们,您只能对它们进行处理以生成新字符串。然后,您可以将此新字符串分配给包含源字符串的同一变量,从而有效地将旧字符串替换为新字符串
在您的情况下,您确认您只想更改输入字符串的第二个单词的第一个字符。然后你可以写
// Split the string in its word parts
string[] parts = name.Split(' ');
// Check if we have at least two words
if(parts.Length > 1)
{
// Get the first char of the second word
char c = parts[1][0];
// Change char to upper following the culture rules of the current culture
c = char.ToUpper(c, CultureInfo.CurrentCulture);
// Create a new string using the upper char and the remainder of the string
parts[1] = c + parts[1].Substring(1);
// Now rebuild the name with the second word first letter changed to upper case
name = string.Join(" ", parts);
}
我使用以下代码片段让它工作:
static void Main(string[] args)
{
int index;
string name = "Jefferey steinberg";
string lastName;
index = name.IndexOf(' ');
lastName = name[index+1].ToString().ToUpper();
name = name.Remove(index + 1, 1);
name = name.Insert(index + 1, lastName);
Console.WriteLine(name);
Console.ReadLine();
}
有一个更好的方法吗?
您可以尝试使用 ToTitleCase 函数,因为它比在字符串中搜索空格并将下一个字母大写要好。
例如:
string s = "Jeffrey steinberg smith";
TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
string uppercase = ti.ToTitleCase(s);
Result: Jeffrey Steinberg Smith
这不是真的
c# 字符串不是 c 中的数组。
他们是[]char
。您可以迭代它们,获取长度等。也是不可变的。见MSDN:
值为文本的字符串。在内部,文本存储为 Char 对象的顺序只读集合。
本着上下文的精神,这种(我同意非最优雅的)解决方案即使对于长全名也应该有效:
public static string GetTitleCase(string fullName)
{
string[] names = fullName.Split(' ');
List<string> currentNameList = new List<string>();
foreach (var name in names)
{
if (Char.IsUpper(name[0]))
{
currentNameList.Add(name);
}
else
{
currentNameList.Add(Char.ToUpper(name[0]) + name.Remove(0, 1));
}
}
return string.Join(" ", currentNameList.ToArray()).Trim();
}