Remove double quotes from NSString

2019-01-25 20:23发布

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?

6条回答
倾城 Initia
2楼-- · 2019-01-25 20:54

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

[mString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mString length])];
查看更多
Deceive 欺骗
3楼-- · 2019-01-25 20:54

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楼-- · 2019-01-25 20:54

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

查看更多
Anthone
5楼-- · 2019-01-25 20:54

You can use

string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [string length])];
查看更多
Viruses.
6楼-- · 2019-01-25 21:04

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?

查看更多
放我归山
7楼-- · 2019-01-25 21:16

How about this ?

NSCharacterSet *quoteCharset = [NSCharacterSet characterSetWithCharactersInString:@"\""];
NSString *trimmedString = [toBeTrimmedString stringByTrimmingCharactersInSet:quoteCharset];
查看更多
登录 后发表回答