小编Eri*_*way的帖子

String.Substring如何比String.Split更有效?

Joe Duffy的博客暗示使用string.Substring效率比string.Split.

我不知道它是否说该Substring方法没有分配新的字符串,或者它是否更有效,因为它没有进行任何不需要的分配.你能解释它如何更有效率并展示一个例子.

我理解他的第一个例子是创建一个数组然后处理数组中的每个字符串.

string str = ...;
string[] substrs = str.Split(',');
foreach (string subtr in substrs) {
Process(substr);
}
Run Code Online (Sandbox Code Playgroud)

如何提高效率

string str = ...;
int lastIndex = 0;
int commaIndex;
while ((commaIndex = str.IndexOf(',', commaIndex)) != -1) {
    Process(substr, lastIndex, commaIndex);
    lastIndex = commaIndex + 1;
Run Code Online (Sandbox Code Playgroud)

我看到的是使用 String.IndexOf查找逗号的索引然后处理字符串.我假设他打算String.Substring在处理过程中使用它来提取数据.下面的评论之一表明他可能会逐字逐句地提出它.他是否会拉动角色,直到他击中下一个可能构建一系列char的逗号?

.net c#

5
推荐指数
1
解决办法
3879
查看次数

标签 统计

.net ×1

c# ×1