Remove double quotes from NSString

Deadly 提交于 2019-12-18 05:11:11

问题


How do I remove double quotes from an NSString. Example:

//theMutableString: "Hello World"

[theMutableString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:(NSRange){0,[theMutableString length]}]

It doesn't seem to work, maybe since I had to escape the " in the replaceOccurrencesOfString?


回答1:


Use the NSMakeRange function instead of your cast. This'll work:

[mString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mString length])];



回答2:


How about this ?

NSCharacterSet *quoteCharset = [NSCharacterSet characterSetWithCharactersInString:@"\""];
NSString *trimmedString = [toBeTrimmedString stringByTrimmingCharactersInSet:quoteCharset];



回答3:


Assuming the mString bit is a typo. I ran this code and the answer was as expected

NSMutableString * theMutableString = [[NSMutableString alloc] initWithString:@"\"Hello World!\""];
NSLog(@"%@",theMutableString);

[theMutableString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:(NSRange){0,[theMutableString length]}];

NSLog(@"%@",theMutableString);

[theMutableString release];

Output

2010-01-23 15:49:42.880 Stringtest[2039:a0f] "Hello World!"
2010-01-23 15:49:42.883 Stringtest[2039:a0f] Hello World!

So it mString was a typo in your question, then your code is correct and the problem is elsewhere. If mString is a typo in your code than that would be the issue.




回答4:


What happens if you use NSMakeRange(0, [theMutableString length]) instead of trying to cast an inline struct?




回答5:


I works perfectly on my end (I copy-pasted your replace line), with both NSMakeRange and the inline struct cast. Are you sure the quotes in your NSString are really the ASCII character 0x22?




回答6:


You can use

string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];


来源:https://stackoverflow.com/questions/2124860/remove-double-quotes-from-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!