簡體   English   中英

如何在字符串中間大寫字母?

[英]How to uppercase a letter in the middle of a string?

我正在嘗試大寫位於第一個空格之后的字符串中的第一個字母:

string name = "Jeffrey steinberg";

我正在嘗試在steinberg中大寫S。 我不確定該怎么做。 我試過弄亂w / 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制作標題大寫。

您可以嘗試函數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();
}

如果要替換字符串中的單個char,則不能對該字符串進行操作,以替換char數組中的元素。 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();
    }

有一個更好的方法嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM