Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last word in a string in Objective-c

Tags:

objective-c

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 "

like image 601
user462455 Avatar asked Jan 08 '13 01:01

user462455


People also ask

How do you remove the last character of a string in Objective C?

(string. length>0) returns 0 thus making the code return: string = [string substringToIndex:string. length-0];

How to remove last word from string?

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.

How to remove last string from path in c#?

The C# String. Remove method can be used to remove last characters from a string in C#.

How to trim last word in string 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(' ').


1 Answers

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"
like image 100
Ramy Al Zuhouri Avatar answered Nov 15 '22 09:11

Ramy Al Zuhouri