2012-11-21 53 views
0

我在下面有这段代码,但是我只希望它在字符串中显示最多15个字符。我该怎么做呢?如何在C中限制for循环#

string star = ""; 
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length; i++) 
{ 
    string mem = "*"; 
    star = star + mem; 
} 
+0

一个一个班轮:'串星=新的字符串( '*',Math.Min(15 Model.orgInternalcontact.User.Password.Length))' – vcsjones

+0

什么是你想做什么? –

+0

@vcsjones这不起作用,因为你使用'Math.Max'而不是'Math.Min'。 –

回答

6
string star = ""; 
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length && i < 15; i++) 
{ 
    string mem = "*"; 
    star = star + mem; 
} 

你可以拥有的第二部分的任何条件语句。

+3

实际上不会是......十六个字符吗? =) –

+0

Maaaaaaaaaybe。至少,现在不行了。 –

+0

感谢这工作很好 – Ben

2

执行以下操作:

string star = ""; 
for (int i = 0; i < Math.Min(15, Model.orgInternalcontact.User.Password.Length); i++) 
{ 
    string mem = "*"; 
    star = star + mem; 
} 
+0

感谢这个工程,但我会去为另一个更短。但是,谢谢 – Ben

2
string star = ""; 
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length && i < 15; i++) 
{ 
    string mem = "*"; 
    star = star + mem; 
} 

您可以在声明中有多个比较。

+0

感谢这很好的工作 – Ben

4
string star = new string('*', 
    Math.Min(Model.orgInternalcontact.User.Password.Length, 15)); 
+1

+1消除了笨重和低效的字符串连接。 – Servy

1
string star = ""; 
string mem = "*"; 
var count = Math.Min(15, Model.orgInternalcontact.User.Password.Length); 
for (int i = 0; i < count ; i++) 
{ 
    star = star + mem; 
}