Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用未知数量的变量格式化字符串_C#_Arrays_.net_String - Fatal编程技术网

C# 使用未知数量的变量格式化字符串

C# 使用未知数量的变量格式化字符串,c#,arrays,.net,string,C#,Arrays,.net,String,在C中,我有一个例子,我希望概括以下类型的字符串格式: string original = "[{0}] is a parent of [{1}] who is the brother of [{2}] who is.."; List<string> args = new List<string>() {"Alice", "Bob", "Charlie", "Doug"};

在C中,我有一个例子,我希望概括以下类型的字符串格式:

string original = "[{0}] is a parent of [{1}] who is the brother of [{2}] who is..";
List<string> args = new List<string>() {"Alice", "Bob", "Charlie", "Doug"};

string formattedString = String.Format(original, args);
这里的主要挑战是,原始字符串可能有未知数量的变量,鉴于列表参数的计数总是应该高于或等于原始字符串中的变量数量,我如何使其工作

string original = "{0} is a parent of {1} who is the brother of {2} who is..";
string[] args = new string[] { "Alice", "Bob", "Charlie", "Doug" };

string formattedString = String.Format(original, args);
尝试上面的代码,它将为您提供预期的输出。
我刚刚将List改为string[]。

计算格式字符串中索引数量的最佳方法可能是模仿它在内部的操作方式。我不会在这里列出超过200行的代码,但其要点是:迭代字符,检查每个字符是否是大括号,而不是转义大括号,等等


一种更简单但更容易出错的方法是使用regex来计算它们,在这种情况下,我将引导您解决这个问题。

不清楚您想要实现什么。如何确定原始字符串是否适合输入参数?如果不是,你希望发生什么?您只描述了完全匹配的情况。如果将列表转换为字符串[]并删除字符串中的[],则String.Format已支持此操作。忽略已提到的代码错误,您需要澄清您所说的“我如何才能使其工作?”…其中“原始字符串可以具有未知数量的变量”?您当前的代码现在在做什么?原始字符串中有三个3变量。同样的代码可以处理1、5或“未知”数量的变量。你应该澄清你在问什么。如果原始字符串可能有未知数量的变量…那么“如何”构造该字符串?为什么要关心其中的“多少”变量?代码仍然可以工作。@00110001,DavidL,我认为很明显,问题在于处理一个包含不确定数量索引的格式字符串,以及提供一个参数列表的要求,该列表至少包含与格式字符串中最大索引相同数量的元素。当然,如果克里希纳普罗希特的意思是别的,那么你是对的,这个问题一点也不清楚:D@JKlen…我想你错过了问题的最后一句话。假设args列表的大小有效。这使得问题变得不清楚,因为当前代码如果修复,仍然可以处理命令范围内的任意数量的参数。
string original = "{0} is a parent of {1} who is the brother of {2} who is..";
string[] args = new string[] { "Alice", "Bob", "Charlie", "Doug" };

string formattedString = String.Format(original, args);