-1

I have the following array:

["Main", "Category 1", "Category2", "Category 3"]

Is there a way to make a copy of this array, but make all of the strings lowercase and replace the spaces with a dash ("-")?

I know I can do this for the replacing of spaces, but I do not know how to iterate over the array.

[string stringByReplacingOccurrencesOfString:@" " withString:@"-"];

My end goal is to have an array that looks like this:

["main", "category-1", "category2", "category-3"]

Thank you in advance for the help!

jape
  • 2,861
  • 2
  • 26
  • 58

1 Answers1

1

You would need to loop through the array and call lowercaseString to make the string lower, and then for replacing spaces, I split the string into components using componentsSeparatedByCharactersInSet: then combine the component with componentsJoinedByString:

For example:

NSString *string = @"Company 1";

NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" "];

string = [[[string lowercaseString]
            componentsSeparatedByCharactersInSet: doNotWant]
            componentsJoinedByString: @"-"];

EDIT:

Assuming the array is of NSMutableArray, you can call replaceObjectAtIndex:withObject (otherwise you would have to copy each index into a new array)

for (int i = 0; i < array.count; i++) {
    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@" "];
    [array replaceObjectAtIndex:i withObject:[[[array[i] lowercaseString] componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @"-"]];
}
Matthew S.
  • 711
  • 1
  • 5
  • 22