【问题标题】:How to get the first char of a string by string interpolation?如何通过字符串插值获取字符串的第一个字符?
【发布时间】:2021-08-24 15:37:36
【问题描述】:
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”的第一个字母?

【问题讨论】:

  • 这是不可能的,不。
  • 绝对不是开箱即用的,但是您可以使用 FormatWith() 构建类似的东西并获得类似 "{name:left:1}" 的东西,然后通过创建自己的处理程序重载使用 "{name:left:1}".FormatWith(new { name }) 调用它。

标签: c# string-interpolation


【解决方案1】:

你真的需要这样做:

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

【讨论】:

  • hmmm... 不是 OP 要求不更改 buildstrings-Method 吗? :-) 显然不是,因为它被标记为答案
  • @dba - 哈哈。我错过了。
【解决方案2】:

这是一个奇怪的要求,没有任何内置支持此功能,但如果您真的必须这样做,您可以编写一个方法来解析索引器,如下所示:

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

【讨论】:

    【解决方案3】:

    您可以添加自定义格式并使用它来代替 [0]。 看这个:Custom format - maximum number of characters

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多