Reputation: 16859
array
is a NSMutableArray
. I am adding some string objects to it.
[array addObject:@"MM-19"];
[array addObject:@"MM-49"];
[array addObject:@"MM-165"];
[array addObject:@"MM-163"];
Now, I need to write a method that will return me a NSString
in the following format :
19-49-165-163
How can this be done ?
Upvotes: 0
Views: 201
Reputation: 14294
Swift 2.0:
let mutableArray = NSMutableArray()
mutableArray.addObject("MM-19")
mutableArray.addObject("MM-49")
mutableArray.addObject("MM-165")
mutableArray.addObject("MM-163")
var finalString = String()
finalString = ""
for stringValue in mutableArray {
let temp: [AnyObject] = stringValue.componentsSeparatedByString("-")
finalString = finalString.stringByAppendingString(String(temp.last)+"-")
}
print("Final String: \(finalString)")
OR
var finalSeperatedString: String = mutableArray.componentsJoinedByString("-")
finalSeperatedString = finalSeperatedString.stringByReplacingOccurrencesOfString("MM-", withString: "")
print("Output String: \(finalSeperatedString)")
}
Upvotes: 0
Reputation: 38162
Another alternative could be:
NSString *combinedStuff = [array componentsJoinedByString:@""];
combinedStuff = [combinedStuff stringByReplacingOccurrencesOfString:@"MM" withString:@""];
if ([combinedStuff hasPrefix:@"-"])
{
combinedStuff = [combinedStuff substringFromIndex:1];
}
Upvotes: 0
Reputation: 4373
Try this code will help,
NSString *finalString = @"" ;
for (NSString *strvalue in array)
{
NSArray *temp= [strvalue componentsSeparatedByString:@"-"];
if ([strvalue isEqualToString:array.lastObject])
{
finalString= [finalString stringByAppendingString:temp.lastObject];
}
else
{
finalString= [finalString stringByAppendingString:[NSString stringWithFormat:@"%@-",temp.lastObject]];
}
}
NSLog(@"%@",finalString);
Upvotes: 0
Reputation: 4675
Here is your solution,
NSString *dashSeperatedString = [array componentsJoinedByString:@"-"] ;
dashSeperatedString = [dashSeperatedString stringByReplacingOccurrencesOfString:@"MM-" withString:@""] ;
NSLog(@"Output : %@", dashSeperatedString);
Upvotes: 5