string a = "123,143,12,612,23"; int i = 0; int len = a.Length; for (int j = 0; j < len; j++) { if (a[j] ==Convert.ToChar(",")) { i = i + 1; } } Response.Write(i.ToString());
貌似这些方法都不是很简单很效率哦,期待高手出现啊 还有在sql里怎么实现对逗号的统计呢?
string aa = "123,143,12,612,23"; string bb = aa.Replace(",", ""); int cc = aa.Length - bb.Length;
C#: string str1 = "123,143,12,612,23"; int count = 0; for (int i = 0; i < str1.Length; ++i) if (str1[i] == ',') count++; Console.WriteLine(count);
declare @str nvarchar(500) declare @icount int set @str=',123,143,12,612,23,45,' set @icount =0 while (CHARINDEX(',', @str)<>0) begin set @str = substring(@str,CHARINDEX(',', @str)+1,len(@str)-CHARINDEX(',', @str)) set @icount =@icount+1 end print @icount
如1楼所讲,按,拆分成数组统计2楼逐个循环统计长度但是如果光要,个数的话我认为取2次长度之后相减最简单效率string a = "123,143,12,612,23"; string b =a.Replace(",",""); int count = a.Length-b.Length;
我认为执行Replace函数肯定还是要遍历一遍字符串,只不过代码比较断
同意,都要遍历字符串,不过用.net自带的函数效率应该高些,总不会比自己写遍历差
sql高手,厉害,不过好复杂啊!不知道性能如何呢?
如果直接对数据库中的记录操作这个比C#里面的方法快,你可以把它写在sql自定义函数.
int rs = Regex.Matches(a,",").Count; 正则表达式的效率也不是太高.
int i = 0;
int len = a.Length;
for (int j = 0; j < len; j++)
{
if (a[j] ==Convert.ToChar(","))
{
i = i + 1;
}
}
Response.Write(i.ToString());
还有在sql里怎么实现对逗号的统计呢?
string aa = "123,143,12,612,23";
string bb = aa.Replace(",", "");
int cc = aa.Length - bb.Length;
string str1 = "123,143,12,612,23";
int count = 0;
for (int i = 0; i < str1.Length; ++i)
if (str1[i] == ',')
count++;
Console.WriteLine(count);
declare @str nvarchar(500)
declare @icount int
set @str=',123,143,12,612,23,45,'
set @icount =0
while (CHARINDEX(',', @str)<>0)
begin
set @str = substring(@str,CHARINDEX(',', @str)+1,len(@str)-CHARINDEX(',', @str))
set @icount =@icount+1
end
print @icount
string b =a.Replace(",","");
int count = a.Length-b.Length;