简体   繁体   English

在iPhone中使用特殊字符后切掉nsstring

[英]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 "." 我是iPhone新手,我想在特殊字符后剪切字符串,让我们举个例子“ works.php”,我想从此字符串中删除“ .php”,这意味着我想删除“。”之后的内容。 what is the code to do that ?? 这样做的代码是什么? thanks in Advance. 提前致谢。

It seems you want to use -stringByDeletingPathExtension . 看来您想使用-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: 如果您真的只需要删除最后一个点之后的字符串,则只需使用(1)的常规算法即可找到最后一个点(2)获得一个子字符串,直到最后一个点为止:

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.. 如果您需要其他删除选项,另一种方法是NSRangesubstringWithRange

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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