簡體   English   中英

如何通過字符串插值獲取字符串的第一個字符?

[英]How to get the first char of a string by string interpolation?

static void BuildStrings(List<string> sentences)
{
    string name = "Tom";
    foreach (var sentence in sentences)
        Console.WriteLine(String.Format(sentence, name));
}
static void Main(string[] args)
{

    List<string> sentences = new List<string>();
    sentences.Add("Hallo {0}\n");
    sentences.Add("{0[0]} is the first Letter of {0}\n");

    BuildStrings(sentences);

    Console.ReadLine();
}

//Expected:
//Hallo Tom
//T is the first Letter of Tom

但我得到了:

System.FormatException:“輸入字符串的格式不正確。”

如何在不更改BuildStrings方法的情況下獲取“Tom”的第一個字母?

你真的需要做這樣的事情:

static void BuildStrings(List<string> sentences)
{
    string name = "Tom";
    foreach (var sentence in sentences)
        Console.WriteLine(String.Format(sentence, name, name[0]));
}

static void Main(string[] args)
{
    List<string> sentences = new List<string>();
    sentences.Add("Hallo {0}\n");
    sentences.Add("{1} is the first Letter of {0}\n");

    BuildStrings(sentences);

    Console.ReadLine();
}

這給了我:

Hallo Tom

T is the first Letter of Tom

這是一個奇怪的要求,沒有內置的東西支持這個,但如果你真的需要,你可以編寫一個方法來解析索引器,如下所示:

public static string StringFormatExtended(string s, params object[] args)
{
    string adjusted =
        Regex.Replace(s, @"\{(\d+)\[(\d+)\]\}", delegate (Match m)
        {
            int argIndex = int.Parse(m.Groups[1].Value);
            if (argIndex >= args.Length) throw new FormatException(/* Some message here */);

            string arg = args[argIndex].ToString();

            int charIndex = int.Parse(m.Groups[2].Value);
            if (charIndex >= arg.Length) throw new FormatException(/* Some message here */);

            return arg[charIndex].ToString();
        });

    return string.Format(adjusted, args);
}

用法:

static void BuildStrings(List<string> sentences, string name)
{
    foreach (var sentence in sentences)
        Console.WriteLine(StringFormatExtended(sentence, name));
}

static void Main(string[] args)
{
    string name = "Tom";

    List<string> sentences = new List<string>();
    sentences.Add("Hello {0}\n");
    sentences.Add("{0[0]} is the first Letter of {0}");
    sentences.Add("{0[2]} is the third Letter of {0}");

    BuildStrings(sentences, name);

    Console.ReadLine();
}

Output:

Hello Tom

T is the first Letter of Tom
m is the third Letter of Tom

您可以添加自定義格式並使用它代替 [0]。 看這個:自定義格式 - 最大字符數

暫無
暫無

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

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