我正在尝试从选定的字符串中删除转义序列(\ p)(以便在我的代码中的其他位置重用)。我想创建一个单独的对象来保存清理后的字符串。喜欢这个
(pseudo code)
NSString *stringWithEscSequence = anEdgewoodSecretPlace.placeName;
NSString *stringWithoutEscSequence = [removeTheEscSequenceP stringWithEscSequence];
(where removeTheEscSequenceP is what I'm trying to figure out how to do)
...
我玩过NSString格式,我发现了相关的问题 Position of a character NSString 和 how to replace one substring with another in Objective C? 我可以在第二个帖子中使用转义序列后面的子字符串。所以我想我应该尝试找到转义序列的实际索引。但我无法弄清楚如何做到这一点。此外,我认为这可能是一种不那么混乱,更直接的方式,我没想到。
我正在玩第一个发布的想法,虽然我知道我处于一种原始模式。但是一旦我尝试用“\”替换“ABCD”。我收到错误'Missing terminating'“”=除非我把ABCD字符串放回去,我没有错过任何引号。我认为这是因为\字符的特殊性。
即使我能弄清楚如何搜索“\”然后再搜索“p”,我认为这不是真正解决此问题的最佳方式
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"ABCD"];
NSRange range2 = [testCleanString rangeOfCharacterFromSet:charSet];
if (range2.location == NSNotFound) {
NSLog (@"Didn't find esc sequence");
} else {
NSLog (@"range.location is %lu",(unsigned long)range2.location );
}
答案 0 :(得分:0)
你可以试试这个:
NSString* stringWithoutEscSequence = [stringWithEscSequence stringByReplacingOccurrencesOfString:@"stringToRemove" withString:@"replacement"];
如果您想替换多个字符,您可以这样做:
NSCharacterSet* toRemove = [NSCharacterSet characterSetWithCharactersInString:@"\n\p\t"];
NSString* stringWithoutEscSequence = [[stringWithEscSequence componentsSeparatedByCharactersInSet:toRemove] componentsJoinedByString: @""];