开发者

C# string manipulation, why this doesn't work?

int i = 1;
for (; i <= 10; i++)
{
    string str = "test{0}" , i;
    Console.WriteLine(str);
}

So this code doesn't work, and I want to know the reason, and wh开发者_开发技巧at are correct ways to produce this?


I think you meant to wrap that with a String.Format call.

string str = String.Format("test{0}", i);


You should try this syntax:

for (int i = 1; i <= 10; i++) {     
    string str = String.Format("test{0}", i);
    Console.WriteLine(str); 
} 


The way you have defined your string doesn't look correct to me at all. I'm guessing the code you're looking for is:

int i = 1;
for(; i <= 10; i++)
{
    string str = string.Format("test{0}", i);
    Console.WriteLine(str);
}

But in that case there's really no reason to create a new string and call Format() for every iteration. You can create a single string and let Console.WriteLine() handle the formating.

string str = "test{0}";

for(int i = 1; i <= 10; i++)
    Console.WriteLine(str, i);


My guess is you want something like this:

for(int i=1;i<=10;i++)
    Console.WriteLine(String.Format("test{0}",i);

You can put any number of things in brackets, separate each input with a comma.

string Month = "Jan";
int day = 21;
string temp = String.Format("Today is:{0} - {1}/{2}",Month,day,2011);

temp gets the value "Today is:Jan - 21/2011"

In the future the desired output would be helpful.

Edit: spelling


int i;  
for (; i <= 10; i++)  Console.WriteLine("test{0}", i); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜