Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

But I got:

System.FormatException: 'Input string was not in a correct format.'

How to get the first Letter of "Tom" without changing the BuildStrings Method?

like image 734
ojesseus1 Avatar asked Nov 20 '25 07:11

ojesseus1


1 Answers

You really need to do something like this:

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

That gives me:

Hallo Tom

T is the first Letter of Tom
like image 157
Enigmativity Avatar answered Nov 21 '25 21:11

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!