当前位置: 首页 > 编程语言 > C#

C#字符串中字符的第三索引分享

时间:2023-04-11 10:43:12 C#

C#字符串中字符的第三索引有没有获取字符串中字符第三索引的命令?例如:错误:file.ext:第10行:无效命令[test:)]在上面的句子中,我想要第3个冒号的索引,即10旁边的那个。我该怎么做?我知道string.IndexOf和string.LastIndexOf,但在这种情况下,我想在第三次使用时获取字符的索引。String.IndexOf将获得第一个索引,但有重载以提供起点。所以你可以使用第一个IndexOf加1的结果作为下一个的起点。然后只需累积索引足够的次数:varoffset=myString.IndexOf(':');offset=myString.IndexOf(':',offset+1);varresult=myString.IndexOf(':',offset+1);添加错误处理,除非您知道myString至少包含三个冒号。你可以这样写:publicstaticintCustomIndexOf(thisstringsource,chartoFind,intposition){intindex=-1;for(inti=0;i编辑:显然你必须按如下方式使用它:intcolonPosition=myString.CustomIndexOf(',',3);我想你想将该字符串解析为不同的部分。publicstaticvoidMain(){varinput=@"error:file.ext:line10:invalidcommand[test(:]";varsplitted=input.Split(separator:new[]{":"},count:4、options:StringSplitOptions.None);varseverity=splitted[0];//“error”varfilename=splitted[1];//“file.ext”varline=splitted[2];//“第10行"varmessage=splitted[3];//"invalidcommand[test(:]"}有几个很好的解决方法-但我决定尝试使用表达式来编写它。私人诠释?GetNthOccurrence(stringinputString,charcharToFind,intoccurrenceToFind){inttotalOccurrences=inputString.ToCharArray().Count(c=>c==charToFind);}如果(totalOccurrencesnew{Position=r,Char=inputString[r],Count=1}).Where(r=>r.Char==charToFind);返回charIndex.Select(c=>new{c.Position,c.Char,Count=charIndex.Count(c2=>c2.Positionr.Count==occurrenceToFind).Select(r=>r.Position).First();}并测试证明它:Assert.AreEqual(0,GetNthOccurrence(input,'h',1));Assert.AreEqual(3,GetNthOccurrence(input,'l',2));Assert.IsNull(GetNthOccurrence(input,'z',1));Assert.IsNull(GetNthOccurrence(input,'h',10));你可以调用.IndexOf(char,position)从所需的位置搜索,所以你应该调用它3次(但是,在每次调用之后,您还应该检查是否找到了某些东西)。intpos=-1;for(intk=0;k有点难看,但另一种方法(对其他人已经发布)有效:publicintFindThirdColonIndex(stringmsg){for(inti=0,colonCount=0;i这是(forstringinsteadofchar)的递归实现——作为扩展方法,模仿框架方法的格式。您需要做的就是在扩展方法中将“字符串值”更改为“字符值”并相应地更新测试,它会起作用……如果有人感兴趣,我很乐意这样做并发布它?publicstaticintIndexOfNth(thisstringinput,stringvalue,intstartIndex,intnth){if(nth另外,这里有一些(MBUnit)单元测试可能会帮助你(证明它是正确的):[测试]publicvoidTestIndexOfNthWorksForNth1(){conststringinput="foobarbaz";Assert.AreEqual(3,input.IndexOfNth("",0,1));}[Test]publicvoidTestIndexOfNthWorksForNth2(){conststringinput="foowhatthedeucekthxbai";Assert.AreEqual(21),input.IndexOfNth("",0,2));}[Test]publicvoidTestIndexOfNthWorksForNth3(){conststringinput="foowhatthedeucekthxbai";Assert.AreEqual(34,input.IndexOfNth("",0,3));}请参阅有关类似问题的答案:https://stackoverflow.com/a/46460083/7673306它提供了一种方法来查找指定字符串中特定字符第n次出现的索引。针对你的具体情况,具体实现如下:以上是C#学习教程分享的全部内容:C#字符串中字符的第三索引,如果对大家有用,需要进一步了解C#学习教程,希望大家会多关注---intindex=IndexOfNthCharacter("error:file.ext:line10:invalidcommand[test:)]",3,':');本文收集自网络,不代表立场。如涉及侵权请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢