简体   繁体   中英

cut nsstring after a special character in iphone

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.

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;
}

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.

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM