I have a string coming from server. I am identifying a particular substring and then breaking the main string at that substring.
NSString *string = /* getting from server */;
NSString *strAddress = /* Substring of string */;
NSArray *arr = [string componentsSeparatedByString:strAddress];
NSString *strBeforeAddress = [arr objectAtIndex:0];
This works perfectly fine when strAddress has something before it. But in some cases it completely gives a strange result. For example, when
string = @"cxzcvxcv\n14, Beaven Dam Road\nVail, CO81657";
strAddress = @"14, Beaven Dam Road\nVail, CO81657";
I get only one object in arr, the complete string, which I think is wrong. It should give result as 2 objects: cxzcvxcv and blank object. However, when
string = @"14, Beaven Dam Road\nVail, CO81657";
strAddress = @"14, Beaven Dam Road\nVail, CO81657";
the array arr in this case has 1 object, the complete string. Can someone please explain what is going on here?
From the NSString Class Reference discussion on the method componentsSeparatedByString:
The substrings in the array appear in the order they did in the receiver. Adjacent occurrences of the separator string produce empty strings in the result. Similarly, if the string begins or ends with the separator, the first or last substring, respectively, is empty. For example, this code fragment:
NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];produces an array
{ @"Norman", @"Stanley", @"Fletcher" }.If list begins with a comma and space—for example,
", Norman, Stanley, Fletcher"—the array has these contents:{ @"", @"Norman", @"Stanley", @"Fletcher" }If list has no separators—for example,
"Norman"—the array contains the string itself, in this case{ @"Norman" }.
The output of your two test cases are:
NSString *string = @"cxzcvxcv\n14, Beaven Dam Road\nVail, CO81657";
NSString *strAddress = @"14, Beaven Dam Road\nVail, CO81657";
NSLog(@"%@",[string componentsSeparatedByString:strAddress]);
outputs
(
"cxzcvxcv\n",
""
)
as expected. And for the second case
NSString *string = @"14, Beaven Dam Road\nVail, CO81657";
NSString *strAddress = @"14, Beaven Dam Road\nVail, CO81657";
NSLog(@"%@",[string componentsSeparatedByString:strAddress]);
outputs
(
"",
""
)
again, as expected. I see no problem here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With