Get Second to last character position from string

前端 未结 10 1832
再見小時候
再見小時候 2020-12-19 08:11

I have a dynamically formed string like - part1.abc.part2.abc.part3.abc

In this string I want to know position of second to last \".\" so that i can split string as

10条回答
  •  一个人的身影
    2020-12-19 08:44

    You can use the String.LastIndexOf('.') method to get the position of the last full-stop/period, then use that position in a second call to LastIndexOf('.') to get the last but one, e.g.:

    string aString = "part1.abc.part2.abc.part3.abc";
    int lastPos = aString.LastIndexOf('.');
    
    int lastPosButOne = aString.LastIndexOf('.', lastPos - 1);
    

    But I'd recommend using String.Split('.') which will give you an array of the string parts, then you can take the last but one, e.g.

    string aString = "part1.abc.part2.abc.part3.abc";
    string[] parts = aString.Split('.');
    
    string lastPartButOne = parts[parts.Length - 1];
    

提交回复
热议问题