我随机尝试使这段代码有效。我遇到的问题是我无法在某些字符串中找到字符串,因为char只占用一个字符。
还有其他办法吗?
例如我可以在"e"
中找到多少个字符"excellent"
,但我无法找到"ll"
。它会给我错误。
我使用的代码:
try
{
int count = label1.Text.Split(Convert.ToChar(textBox1.Text)).Length - 1;
MessageBox.Show(count.ToString());
}
catch
{
messagebox.show("error");
}
这就是我使用的原因,试图捕捉错误。
答案 0 :(得分:1)
这是因为您使用的Convert.ToChar(...)
只能将string
转换为char
(即由单个字符组成,但是& #34; ll"由两个字符组成)。
您可以为string
创建一个扩展程序来执行您想要的操作:
public static class StringExtensions {
public static List<int> AllIndexesOf(this string str, string value) {
if (String.IsNullOrEmpty(value))
throw new ArgumentException("the string to find may not be empty", "value");
List<int> indexes = new List<int>();
for (int index = 0; ; index += value.Length) {
index = str.IndexOf(value, index);
if (index == -1)
return indexes;
indexes.Add(index);
}
}
}
然后就像使用它一样:
int count = label1.Text.AllIndexesOf(textBox1.Text).Count;