3

I'm new in iPhone, I want to cut a string after a special character, lets take this example "works.php" , I want to remove ".php" from this string meaning that I want to remove what's after "." what is the code to do that ?? thanks in Advance.

3 Answers 3

5

It seems you want to use -stringByDeletingPathExtension.

[@"works.php" stringByDeletingPathExtension]   // becomes @"works".

Note that this method deletes path extensions, which is not exactly the same as "remove what's after a dot". Please read the reference I've linked above for detail.

If you really just need to remove the string after the last dot, just use the conventional algorithm of (1) find the last dot (2) get a substring until the last dot:

NSString* input = @"works.php";
NSRange lastDotRange = [input rangeOfString:@"." options:NSBackwardsSearch];
if (lastDotRange.location != NSNotFound) {
    return [input substringToIndex:lastDotRange.location];
} else {
    return input;
}
0
4

For the specific example you can use:

- (NSString *)stringByDeletingPathExtension

The more general way to do what you want is:

NSString *originalString = @"works.php";  
NSString *finalString = 
[[originalString componentsSeparatedByString:@"."] objectAtIndex: 0];

You can replace the dot character with any character you want.

0
1

You can use:

myString = @"anything.php";
myString = [myString stringByReplacingOccurrencesOfString:@".php" withString:@""];

The advantage of this is that you can put anything to remove, not only a path. For example:

myString = @"anything-123";
myString = [myString stringByReplacingOccurrencesOfString:@"-123" withString:@""];

Another approach is NSRange and substringWithRange if you want other removing options..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.