-3

I have a string like: "mocktail, wine, beer"

How can I convert this into: "mocktail", "wine", "beer"?

Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
piyush
  • 137
  • 1
  • 3
  • 8

4 Answers4

5

the following gives you the desired result:

NSString *_inputString = @"\"mocktail, wine, beer\"";
NSLog(@"input string : %@", _inputString);
NSLog(@"output string : %@", [_inputString stringByReplacingOccurrencesOfString:@", " withString:@"\", \""]);

the result is:

input string : "mocktail, wine, beer"
output string : "mocktail", "wine", "beer"
holex
  • 23,961
  • 7
  • 62
  • 76
2

You need to use:

NSArray * components = [myString componentsSeparatedByString: @", "];
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
0
NSString *string = @"mocktail, wine, beer";
//remove whitespaces
NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

//get array of string
NSArray *array = [trimmedString componentsSeparatedByString:@","];
NSMutableArray *newArray = [[NSMutableArray alloc] init];

for (NSString *trimmedString in array) {
    NSString *newString = [NSMutableString stringWithFormat:@"'%@'", trimmedString];
    [newArray addObject:newString];
}

//merge new strings
NSString *finalString = [NSString stringWithFormat:@"%@", [newArray objectAtIndex:0]];

for (NSInteger i = 1; i < [newArray count]; i++) {
        finalString = [NSString stringWithFormat:@"%@, %@", finalString, [newArray objectAtIndex:i]];
}
Chris
  • 26
  • 3
-1

Without knowing spesifically about iOS or objective-c, I assume you could use a split function.

In almost any higher level programming language there is such a function.

Try: Objective-C split

This gets you an array of Strings. You can then practically do with those what you want to do, e.g. surrounding them with single quotes and appending them back together. :D

Community
  • 1
  • 1
LuigiEdlCarno
  • 2,410
  • 2
  • 21
  • 37