我在下面有这段代码,但是我只希望它在字符串中显示最多15个字符。我该怎么做呢?如何在C中限制for循环#
string star = "";
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length; i++)
{
string mem = "*";
star = star + mem;
}
我在下面有这段代码,但是我只希望它在字符串中显示最多15个字符。我该怎么做呢?如何在C中限制for循环#
string star = "";
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length; i++)
{
string mem = "*";
star = star + mem;
}
string star = "";
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length && i < 15; i++)
{
string mem = "*";
star = star + mem;
}
你可以拥有的第二部分的任何条件语句。
执行以下操作:
string star = "";
for (int i = 0; i < Math.Min(15, Model.orgInternalcontact.User.Password.Length); i++)
{
string mem = "*";
star = star + mem;
}
感谢这个工程,但我会去为另一个更短。但是,谢谢 – Ben
string star = "";
for (int i = 0; i < Model.orgInternalcontact.User.Password.Length && i < 15; i++)
{
string mem = "*";
star = star + mem;
}
您可以在声明中有多个比较。
感谢这很好的工作 – Ben
string star = new string('*',
Math.Min(Model.orgInternalcontact.User.Password.Length, 15));
+1消除了笨重和低效的字符串连接。 – Servy
string star = "";
string mem = "*";
var count = Math.Min(15, Model.orgInternalcontact.User.Password.Length);
for (int i = 0; i < count ; i++)
{
star = star + mem;
}
一个一个班轮:'串星=新的字符串( '*',Math.Min(15 Model.orgInternalcontact.User.Password.Length))' – vcsjones
什么是你想做什么? –
@vcsjones这不起作用,因为你使用'Math.Max'而不是'Math.Min'。 –