C#一组字符串数组如何让每一个字母首字母大写
时间: 2023-07-04 21:24:14 浏览: 81
你可以使用 C# 中的 `CultureInfo` 和 `TextInfo` 类来将每个字符串中的单词首字母大写。这里提供一个示例代码来实现这个功能:
```csharp
using System.Globalization;
...
string[] strings = { "hello world", "good morning", "how are you" };
TextInfo ti = CultureInfo.CurrentCulture.TextInfo;
foreach (string s in strings)
{
string[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
words[i] = ti.ToTitleCase(words[i]);
}
string result = string.Join(" ", words);
Console.WriteLine(result);
}
```
这个代码会输出以下结果:
```
Hello World
Good Morning
How Are You
```
这里使用 `CultureInfo.CurrentCulture.TextInfo` 获取当前系统的文化信息,然后使用 `ToTitleCase` 方法将每个单词的首字母大写。最后使用 `string.Join` 方法连接每个单词,并在它们之间添加一个空格来形成一个新的字符串。
相关问题
c# 判断文件 是否包含 字符串数组中的一个
您可以使用以下代码来判断文件是否包含字符串数组中的一个:
```csharp
string[] keywords = {"string1", "string2", "string3"}; // 字符串数组
string filePath = "file.txt"; // 文件路径
string fileContent = File.ReadAllText(filePath); // 读取文件内容
foreach (string keyword in keywords)
{
if (fileContent.Contains(keyword))
{
Console.WriteLine("文件包含字符串: " + keyword);
break;
}
}
```
该代码将字符串数组中的每个关键字与文件内容进行比较,如果文件内容包含任何一个关键字,则打印出该关键字。
c# 字符串第一个字母大写
可以使用以下代码将 C# 字符串的第一个字母大写:
```csharp
string str = "hello world";
if (!string.IsNullOrEmpty(str))
{
str = char.ToUpper(str[0]) + str.Substring(1);
}
```
这段代码首先检查字符串是否为空或 null,然后将第一个字母转换为大写,并将其与字符串的其余部分拼接起来。