使用String.Format时,使用{0},{1},{2}等来引用要放在字符串中的变量,例如:
string s = String.Format("{0} {1}", "Like", "this.");
有没有什么办法可以在花括号内使用字符串值而不是整数。这样输入字符串就是:
"{word1} {word2}"
我这样做是因为我有一个长文本文件,其中包含需要填写的区域。有太多区域要有一个有序的变量列表,可以重复变量。
那么我如何使用类似于String.Format的方法使用字符串名而不是使用索引?
答案 0 :(得分:2)
String.Format
无法做到这一点。你可以这样做:
string result = formatString.Replace("{word1}", replacement);
假设您有一个字体,其中占位符为键,替换为值,您可以这样做:
Dictionary<string, string> words = new Dictionary<string, string>();
words["{word1}"] = "Hello";
words["{word2}"] = "World!";
StringBuilder result = new StringBuilder("{word1} {word2}");
foreach (string key in words.Keys)
result.Replace(key, words[key]);
string finalResult = result.ToString();
我在这里使用StringBuilder
来确保不会在每个Replace
上复制字符串,如果我在这里使用string
就是这种情况。
答案 1 :(得分:1)
String.Format没有内置的这种功能,如何通过Custom Format strings
实现这一目标或者您可以参考文章Fun With Named Formats, String Parsing, and Edge Cases