取这个字符串中指定字符串的个数

efbbs_007 2011-04-25 11:57:51
字符串如下:1;1|1;8|1;10|2;1|3;7|4;9|1;3|2;1|

获取这个字符串中"1;1"的个数,"1:2"的个数,“1:3”的个数,直到“1:i”的个数,“i”是个整数。

请问这样的方法应该怎样写,用正则表达式可能比较好一点,可是小弟的正则差的很,只好请教各位大侠了,能不能写个方法,不甚感激。。。
...全文
544 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
JTZP007 2013-04-24
  • 打赏
  • 举报
回复
学习了
erpangchouchou 2011-10-11
  • 打赏
  • 举报
回复
学习一下
studywcf_008 2011-04-27
  • 打赏
  • 举报
回复
谢谢大家,方法都不错啊。。。
-过客- 2011-04-26
  • 打赏
  • 举报
回复
try...

        /// <summary>
/// 获取指定字符串的个数
/// </summary>
/// <param name="src">源字符串</param>
/// <param name="arg">指定字符串,格式i;i,如1;2</param>
/// <returns></returns>
private int getCount(string src, string arg)
{
Regex reg = new Regex(@"\b" + Regex.Escape(arg) + @"\b");
return reg.Matches(src).Count;
}
claymore1114 2011-04-26
  • 打赏
  • 举报
回复

string str = "1;1|1;8|1;10|2;1|3;7|4;9|1;3|2;1|";
var query = str.Split('|').Where(w => w.StartsWith("1") && w.Length > 0)
.GroupBy(g => g)
.Select(s => new { key = s.Key, count = s.Count() });
foreach循环出来

Just4life 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 q107770540 的回复:]
C# code

void Main()
{
string str="1;1|1;8|1;10|2;1|3;7|4;9|1;3|2;1|1;1";
string temp="1;1"; //自己定义
int count=str.Split('|').Count(s=>s==temp);
Console.WriteLine(count); //2
}
……
[/Quote]

这种方法不错,+++
phommy 2011-04-26
  • 打赏
  • 举报
回复
1;1:1个
1;3:1个
1;8:1个
1;10:1个
Press any key to continue . . .
phommy 2011-04-26
  • 打赏
  • 举报
回复

static void Main(string[] args)
{
string s = "1;1|1;8|1;10|2;1|3;7|4;9|1;3|2;1|";
List<int> l = new List<int>();
int iTmp;
foreach (var item in from m in s.Split('|')
where m.StartsWith("1;") && m.Length > 2
select m.Substring(2))
{
if (!int.TryParse(item, out iTmp))
{
continue;
}
while (l.Count <= iTmp)
{
l.Add(0);
}
l[iTmp]++;
}

for (int i = 0; i < l.Count; i++)
{
if (l[i]>0)
{
Console.WriteLine("1;" + i + ":" + l[i] + "个");
}
}
}
kingdom_0 2011-04-26
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 q107770540 的回复:]

C# code

void Main()
{
string str="1;1|1;8|1;10|2;1|3;7|4;9|1;3|2;1|1;1";
string temp="1;1"; //自己定义
int count=str.Split('|').Count(s=>s==temp);
Console.WriteLine(count); //2
}
[/Quote]
兔子党是什么党派,人员好像挺充沛,并且基本都有官衔在身啊。
拿凤姐抵债 2011-04-26
  • 打赏
  • 举报
回复
///获取这个字符串中"1;1"的个数,"1:2"的个数,“1:3”的个数,直到“1:i”的个数,“i”是个整数。
void GetCount FromString(string source,string strSearching)
{
for(int i = 1; i < 10;i++)
{
string strSearching = "1:" & i.ToString();
int count = (source.Length - source.Replace(strSearching).Length)/strSearching.Length;
MessageBox.Show("The count of " + strSearching + " is " + count.ToString());
}
}

q107770540 2011-04-26
  • 打赏
  • 举报
回复

void Main()
{
string str="1;1|1;8|1;10|2;1|3;7|4;9|1;3|2;1|1;1";
string temp="1;1"; //自己定义
int count=str.Split('|').Count(s=>s==temp);
Console.WriteLine(count); //2
}

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧