如何替换字符串
如果我们必须静态替换
这样的字符串
String.Format("this is my string {0} & {1}","First","second");
但是如果我动态地得到{0},{1},.. {n}
该怎么办?
如何通过UI中的参数轻松替换n个元素?
Hi,
If we have to statically replace string like String.Format("this is my string {0} & {1}","First","second");
But what if I get dynamically {0},{1},..{n}
How can I do it easily replace n elements with my parameters from UI?
String dynString = "This is a dynamic string {0} & {1}";
String[] replaceString = new String[] { "First", "Second" };
Console.Write(String.Format(dynString, replaceString));
Console.Read();
我写了这样的东西,只是想知道当我得到具有n个元素的replaceString时,它是否对n有效.
谢谢.
I wrote something like this just wondering whether this will work for n when I get this replaceString with n number of elements.
Thanks.
如果您的参数是字符串的集合,则表示您可以像这样使用它
例如:
If your parameter is a collection of string means you can use it like this
ex:
string[] names = { "Anders", "Eric", "Scott", "Duncan" };
Console.Write("My string is ");
foreach (string curr in names)
Console.Write(curr + " ");
如果您清楚地说明了参数的详细信息以及要显示的输出,那么我可以尝试以这种方式显示结果.
If you explain clearly about your parameter details and the output you going to show then I could try to show the result in that way..
如果我正确理解了您的问题,您将获得某种格式字符串并要检查它是否对您的参数数组有效?
您可以去看看使用C#进行转义:字符,字符串,字符串格式,关键字,标识符 [ ^ ],转到 string.format转义部分中的 Bonus 段落.
一个解决方案可能是(通过调整args的数量和格式来使其正常工作...):
If I understand your question correctly, you get some format string and want to check if it is valid for your parameter array?
You may go and have a look at Escaping in C#: characters, strings, string formats, keywords, identifiers[^], go to the Bonus paragraph in the string.format escaping section.
A solution may be (tweak with the number of args and with the formatting to see it work...):
static void Main(string[] args)
{
string dynString = "This is a dynamic string {0} & {1}";
var constArgs = new object[] { "First", "Second" };
string formatted = DynFormat(dynString, constArgs);
Console.WriteLine(formatted ?? "<wrong format>");
}
// get all string format ids in the sequence they appear in the format string
private static IEnumerable<int> GetIds(string format)
{
string pattern = @"\{(\d+)[^\}]*\}";
return Regex.Matches(format ?? string.Empty, pattern, RegexOptions.Compiled)
.Cast<Match>()
.Select(m => int.Parse(m.Groups[1].Value));
}
// true = the format matches the number of args,
// false = the format does not get sufficient args
private static bool HasSufficientArgs(string dynFormat, object[] args)
{
var ids = GetIds(dynFormat).ToArray();
// if no ids (no formatting), then ignore args
// if there are ids, they must have matching args (excess args are ignored)
return (ids.Length == 0)
|| (args != null) && (args.Length > ids.Max());
}
// returns the formatted string if there are sufficent args for the given format,
// returns null otherwise
public static string DynFormat(string dynFormat, params object[] args)
{
return HasSufficientArgs(dynFormat, args)
? string.Format(dynFormat, args)
: null;
}
干杯
安迪
Cheers
Andi