Remove punctuations from NSMutableArray
H开发者_运维问答ow to remove punctuations like "," from an NSMutableArray?
There are no commas in your array or your array elements. When you use NSLog()
to log an array, it uses the NeXTSTEP format, which states that parentheses are used to delimit the array and commas are used to delimit elements.
So if
NSLog(@"%@", myarray);
outputs
( 006d, 0081, 006d, 007f )
this means that the array contains @"006d" in the first position, @"0081" in the second position, "006d" in the third position, and @"007f" in the fourth position.
The commas (and the parentheses) are only part of the representation of the array for output; they’re not part of the array/array elements per se.
Instead of using NSLog()
, you could use the following code snippet to output your array:
NSLog(@"beginning of array");
for (id element in myarray) NSLog(@"%@", element);
NSLog(@"end of array");
which will output something like:
beginning of array
006d
0081
006d
007f
end of array
Edit based on comment: It looks like you want to join the elements of the array. Try this:
NSString *allElements = [myarray componentsJoinedByString:@""];
-[NSArray componentsJoinedByString:]
, as the method name says, joins all the elements in the array, separating them by a string. If you use @""
as the separating string, the elements will be joined one right after another.
If you want to output that string:
NSLog(@"%@", allElements);
Assuming the elements of the array are strings containing comma separated hex numbers, the following produces another NSMutableArray with the anything but alphanumeric chars removed.
NSMutableArray *array = [NSMutableArray arrayWithObject:@"2f,40d,67f"];
for (int i = 0; i < [array count]; i++) {
NSString *element = [array objectAtIndex:i];
NSMutableString *result = [NSMutableString stringWithCapacity:element.length];
NSScanner *scanner = [NSScanner scannerWithString:element];
NSCharacterSet *allowed = [NSCharacterSet alphanumericCharacterSet];
while ([scanner isAtEnd] == NO) {
NSString *buffer;
if ([scanner scanCharactersFromSet:allowed intoString:&buffer]) {
[result appendString:buffer];
} else {
[scanner setScanLocation:([scanner scanLocation] + 1)];
}
}
[array replaceObjectAtIndex:i withObject:result];
}
NSLog(@"array %@", array);
This prints 2f40d67f
but looks like a lot of work to do something so simple. :P
精彩评论