What is the most efficient way to split a string into two parts, in the following way
One part is the last word of string that follows last whitespace character in the string Second part is rest of the string
e.g. "This is a sentence" one part: "sentence" second part: "This is a " //Note there is whitespace at the end of this string
"This is a " one part: "" second part: "This is a "
(string. length>0) returns 0 thus making the code return: string = [string substringToIndex:string. length-0];
In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character. We can achieve that by calling String's length() method, and subtracting 1 from the result.
The C# String. Remove method can be used to remove last characters from a string in C#.
Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator. End result: string lastWord = input. Split(' ').
Try something like this:
NSString *str = @"this is a sentence";
// Search from back to get the last space character
NSRange range = [str rangeOfString: @" " options: NSBackwardsSearch];
// Take the first substring: from 0 to the space character
NSString *str1 = [str substringToIndex: range.location]; // @"this is a"
// take the second substring: from after the space to the end of the string
NSString *str2 = [str substringFromIndex: range.location +1]; // @"sentence"
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