简体   繁体   中英

C# - Have an index array full of strings that I want to print as strings instead of chars

Can someone help me print out a string instead of a char via string interpolation when your strings are indexed in an array? As seen the printed in the if statement - {text[3]} etc.

static void Main(string[] args)
{

    string textDoc = "The first world war occurred in the early 20th century, many countries around the world were originally agnostic to the early battles. An obvious reason why is because there are many countries in the world that do not have relations to nation states that were fighting in the early battles.";

    string[] textSplit = textDoc.Split(" ");
    
    foreach (string text in textSplit) {
        if(text.StartsWith("a")) {
            Console.WriteLine($"Roses {text[2]} red, scarlets {text[2]} blue, this poem doesn't have {text[3]} ending, so embrace the unknown because it is {text[1]}.");
            break;
        }
    }

{text[3]} prints out the char - "a" , instead of a string - "are" .

Thanks.

text is an entire word (as a string)

When your foreach gets to textSplit[12] the value of text will be "around"

If you then use text[3] you'll get the char in position 3 of your string which is 'u'

If you want the entire word "around" just use text instead of text[3]

See this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM