简体   繁体   中英

Format a NSMutableArray object to a string

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 ?

Here is your solution,

NSString *dashSeperatedString = [array componentsJoinedByString:@"-"] ;
dashSeperatedString = [dashSeperatedString stringByReplacingOccurrencesOfString:@"MM-" withString:@""] ;

NSLog(@"Output : %@", dashSeperatedString);

Another alternative could be:

NSString *combinedStuff = [array componentsJoinedByString:@""];
combinedStuff = [combinedStuff stringByReplacingOccurrencesOfString:@"MM" withString:@""];

if ([combinedStuff hasPrefix:@"-"]) 
{
    combinedStuff = [combinedStuff substringFromIndex:1];
}

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);

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)")

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM