如何通过字符串插值获取字符串的第一个字符?

3
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”的第一个字母?


2
这是不可能的,不行。 - ProgrammingLlama
https://github.com/axuno/SmartFormat/wiki/SubString - mjwills
绝对不是开箱即用,但是你可以使用FormatWith()构建类似的东西,并且得到像"{name:left:1}"这样的结果,然后通过创建自己的处理程序重载,使用"{name:left:1}".FormatWith(new { name })进行调用。 - Oliver
3个回答

3

您真的需要像这样做:

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

嗯... OP 的要求不是不改变 buildstrings 方法吗?:-) 显然不是,因为它被标记为答案。 - dba
@dba - 哈哈哈。我错过了那个。 - Enigmativity

1

这是一个奇怪的要求,没有内置的支持,但如果你真的需要,你可以编写一个方法来解析索引器,如下:

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

输出:

Hello Tom

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接