Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Characters and Everything After from String

I am aware of replacing Strings of a String, but that only works if I know exactly what I want to remove.

If I have a String like the following:

"hi-there-this-is-a-test&feature=hi-there"

How do I remove '&feature' and everything that comes after that?

Any help would be greatly appreciated. Thanks in advance!

EDIT: If absolutely necessary to use REGEX, could someone show me how to use it? I am aware it is 10.7 onwards but I'm fine with that. Even better, an example of String trimming or using the NSScanner?

Thanks again everyone.

EDIT: The solution posted below is the correct one, but resulted in a crash for me. This is how I solved the problem:

NSString *newString = [[oldString componentsSeparatedByString: @"&feature="] objectAtIndex:0];
like image 350
Cristian Avatar asked Apr 27 '12 00:04

Cristian


People also ask

How do you remove everything from a string after a character?

Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .

How do you delete everything after a character in a string Python?

To remove everything after the first occurrence of the character '-' in a string, pass the character '-' as a separator in the partition() function. Then assign the part before the separator to the original string variable.

How do I trim a string after a specific character in C#?

Solution 1. string str = "this is a #string"; string ext = str. Substring(0, str. LastIndexOf("#") + 1);


1 Answers

It can be done without REGEX like this:

NSString *string = @"hi-there-this-is-a-test&feature=hi-there";
    NSRange range = [string rangeOfString:@"&feature"];
    NSString *shortString = [string substringToIndex:range.location];
like image 173
rdelmar Avatar answered Oct 19 '22 19:10

rdelmar