C# - 有一个充满字符串的索引数组,我想将其打印为字符串而不是字符

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

当你的字符串被 索引时,有人可以帮助我通过 字符串插值 打印出 字符串 而不是字符吗在数组中? 正如在 if 语句 中打印的那样 - {text[3]}

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]} 打印出字符 - "a",而不是字符串 - "are".

谢谢。

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        //options/configuration values which may work better as parameters
        string source = "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 template = "Roses {0} red, scarlets {1} blue, this poem doesn't have {2} ending, so embrace the unknown because it is {3}.";
        //When true both "around" and "An" will match "a". When false only "around" will
        bool ignoreCase = true;
        int numberOfBlanks = 4;
        //word to use in blanks if not enough matching words are found. use an empty string "" if you don't want anything filled
        string defaultWord = "banana";
        string matchingLetter = "a";
        
        string[] madgabWords = new string[numberOfBlanks];
        Array.Fill(madgabWords, defaultWord);
        
        
        string[] textSplit = source.Split(" ")
          .Where(x=> x.StartsWith(matchingLetter, ignoreCase, null))
          .ToArray();
        
        for(int i = 0; i < textSplit.Length && i < numberOfBlanks; i++)
        {
            madgabWords[i] = textSplit[i];
        }
        
        Console.WriteLine(template, madgabWords);
        //if you are building a string to return or assign to a variable instead of printing directly to console then use:
        var madgab = string.Format(template, madgabWords);
    }
}

你也可以试试online