简体   繁体   English

C#:相当于php sprintf

[英]C#: php sprintf equivalent

I'm looking for a C# equivalent for the php sprintf function. 我正在寻找php sprintf函数的C#等效项。

I have the folowing string: 我有以下字符串:

"There are %s hits, %s are an exact match."

I want %s to be replaced with the numbers that the query returns. 我希望将%s替换为查询返回的数字。 In php I would di the folowing: 在PHP中,我会以下:

$res = sprintf("There are %s hits, %s are an exact match", $number1, $number2);

How do I do this in C#? 如何在C#中执行此操作? I thought about string.replace() but that would only work with 1 piece that should be replaced. 我考虑过string.replace()但只适用于应该替换的1件。 In this case there are multiple. 在这种情况下,有多个。

You are looking for String.Format : 您正在寻找String.Format

String myStr = String.Format("There are {0} hits, {1} are an exact match",
                              number1, number2);

The format specifiers are a bit different than in PHP. 格式说明符与PHP中的格式说明符有所不同。 Here is an article explaining format specifiers . 这是一篇说明格式说明符的文章

您使用String.Format

string s = String.Format("There are {0} hits, {1} are an exact match", number1, number2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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