C#: php sprintf equivalent

南楼画角 提交于 2019-12-14 04:04:59

问题


I'm looking for a C# equivalent for the php sprintf function.

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. In php I would di the folowing:

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

How do I do this in C#? I thought about string.replace() but that would only work with 1 piece that should be replaced. In this case there are multiple.


回答1:


You are looking for 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. Here is an article explaining format specifiers.




回答2:


You use String.Format.

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


来源:https://stackoverflow.com/questions/5329470/c-php-sprintf-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!