如何在Objective c中修剪字符串中的特殊字符

时间:2017-05-03 18:54:36

标签: objective-c nsstring trim

我想修剪字符串

中特殊字符的出现
String  has :    
prevs: Case Number                                                                    
____________________

在这里我想从这个字符串中删除--------这个破折号。我试过这样:

NSCharacterSet *trim = [NSCharacterSet characterSetWithCharactersInString:@"-"];
    NSString *stringNew = [[previousString2 componentsSeparatedByCharactersInSet:trim] componentsJoinedByString:@""];

提前致谢!

4 个答案:

答案 0 :(得分:1)

试试这个:

NSString *stringWithoutDash = [yourString stringByReplacingOccurrencesOfString:@"-" withString:@""];

答案 1 :(得分:0)

NSString *trimedString = [myString stringByReplacingOccurrencesOfString:@"-" withString:@""];

答案 2 :(得分:0)

使用正则表达式,模式[\\s_]{4,}搜索4个或更多空格或下划线字符。

NSString *trimmedString = [previousString2 stringByReplacingOccurrencesOfString:@"[\\s_]{4,}" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, previousString2.length)];

如果下划线字符确实是破折号,则会重新处理模式中的字符。

答案 3 :(得分:0)

您可以使用以下代码删除特殊字符串。

NSString *yourString = @"This is your string with speical character --------";
NSCharacterSet *removedCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"--------"];
NSString *finalString = [[yourString componentsSeparatedByCharactersInSet:removedCharacterSet] componentsJoinedByString:@""];
NSLog (@"Your final string : %@", finalString);