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 part1.abc.part2.abc and part3.abc
let me know is there any direct method available to get this?
Return ValueThe strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned. This example compares the use of strchr() and strrchr() . It searches the string for the first and last occurrence of p in the string.
Use slice notation [length-2:] to Get the last two characters of string Python. For it, you have to get the length of string and minus 2 char.
charAt() method. The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned.
The std::string::find_last_of is a string class member function which is used to find the index of last occurrence of any characters in a string. If the character is present in the string then it returns the index of the last occurrence of that character in the string else it returns string::npos.
string str = "part1.abc.part2.abc.part3.abc";
int ix1 = str.LastIndexOf('.');
int ix2 = ix1 > 0 ? str.LastIndexOf('.', ix1 - 1) : -1;
There are always lovers of Regexes (and jQuery), so I'll give a Regex solution (for the jQuery solution you'll have to wait :-) ):
var match = Regex.Match(str, @"\.[^\.]*\.", RegexOptions.RightToLeft);
int ix = match.Success ? match.Index : -1;
(note that I'm an hater of Regexes, I'm giving it to you so that you can have enough rope to hang yourself if you so choose).
Be aware that I'm using the RegexOptions.RightToLeft
option so that the Regex starts at the last character.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With