开发者

Adding NSMutableString to NSArray

I'm having some trouble adding a mutable string (that has been changed with replaceOccurrencesOfString) to an array. This is related to another question I asked: Remove double quotes from NSString

Here is the code

//original String
NSString *aString = @"\"Hello World\"";
NSLog(@"Original String: %@",aString);

//craete mutable copy
NSMutableString *mString = [aString mutableCopy];

//remove quotes
[mString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [aString length])];
NSLog(@"Mutable String: %@",mString);   

//add to an array
NSArray *anArray = [NSArray arrayWithObject:mString];
NSLog(@"anArray: %@",anArray);

And the result:

2010-01-25 09:01:15.644 Quotes[20058:a0f] Original String: "Hello World"
2010-01-25 09:01:15.662 Quotes[20058:a0f] Mutable String: Hello World
2010-01-25 09:01:15.663 Quotes[20058:a0f] anArray: (
"Hello World"
)

a As you can see开发者_如何转开发, the string is removed of the quotes in mString but when it's added to the array, it still has the double quotes. Any thoughts?


That's because the string has a space in it, and so the array is wrapping it in quotes to make sure you understand that the two words go together. If you were to pull the string back out of the array and search for double quotes, you wouldn't find any.

If the string still had quotes in it and you were to log the array with the quoted string, it would look like:

2010-01-25 10:14:37.818 EmptyFoundation[4131:a0f] (
    "\"Hello world!\""
)


I'm pretty sure your only seeing

2010-01-25 09:01:15.663 Quotes[20058:a0f] anArray: (
"Hello World"
)

Because your printing out the description of the array - try

NSLog(@"The string is: %@", [anArray objectAtIndex:0])

and I'm fairly confident it'll return with

The string is : Hello World
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜