我显然在这里漏掉了什么...
我正在编写一个函数,该函数返回由特定字符串分隔的子字符串数量。以下是相当简单的函数 -
public static FuncError DCount(String v1, String v2, ref Int32 result) {
result = 0;
if (String.IsNullOrEmpty(v1)) {
return null;
}
if (String.IsNullOrEmpty(v2)) {
return null;
}
int ct = 1;
int ix = 0;
int nix = 0;
do {
nix = v1.IndexOf(v2, ix);
if (nix >= 0) {
ct++;
System.Diagnostics.Debug.Print(
string.Format("{0} found at {1} count={2} result = {3}",
v2, nix, ct, v1.Substring(nix,1)));
ix = nix + v2.Length;
}
} while (nix >= 0);
result = ct;
return null;
}
当我使用一个在特定情况下作为分隔符使用的特殊字符进行调用时,问题就出现了。它返回了很多错误的结果。从Debug.Print中可以看出,第一个和最后一个参数应该总是相同的。
þ found at 105 count=2 result = t
þ found at 136 count=3 result = t
þ found at 152 count=4 result = þ
þ found at 249 count=5 result = t
þ found at 265 count=6 result = t
þ found at 287 count=7 result = t
þ found at 317 count=8 result = t
þ found at 333 count=9 result = þ
þ found at 443 count=10 result = þ
þ found at 553 count=11 result = þ
þ found at 663 count=12 result = þ
þ found at 773 count=13 result = þ
þ found at 883 count=14 result = þ
þ found at 993 count=15 result = þ
如果我将þ作为字符传递,它可以正常工作。如果我使用þ作为分隔符来分割字符串,则会返回正确数量的元素。至于错误识别的“t”,结果中有其他未被捕获的“t”,因此这不是字符转换问题。
感到困惑...
谢谢