1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
String[] result = new String[10]; //存放查找到的串 int num = 0; String info="**************"; //这就是原始的字符串数据 string startString = "id=\""; //要查找的起始串 string endString = "\" type="; //要查找的结束串 int startIndex = 0; int endIndex = 0; //假设已经目标字符串中最多含有10个我们需要获取的元素 while (num < result.Length) { startIndex = info.IndexOf(startString, endIndex); if (startIndex == -1) { Console.WriteLine("查找完毕..."); break; } else { startIndex += 5; endIndex = info.IndexOf(endString, startIndex); result[num] = info.Substring(startIndex, endIndex - startIndex);//提取起始和结束串之间的子字符串 num++; } } |
最终目的很简单,已知一个字符串,要获取里面的所有符合形式的子串里面的序列号,也就是startString和endString之间会有一个序列号,需要检索并罗列出原始字符串中所有的序列号,然后打印出来以供选择。google到的两个字符串处理方法IndexOf()和Substring(),前者用来搜索特定格式的编译地址,后者依获取的偏移地址得到最终的序列号串:
1 2 3 4 5 6 7 |
int string.IndexOf(string value, int startInex) (+ 8 overload(s)) Reports the index of the first occurrence of the specified System.String in this instance. The search starts at a special character position. string string.Substring(int startIndex, int length) (+ 1 overload(s)) Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length. |