开发者

How to split a string with the uppercase character in iPhone [closed]

Closed. This question needs to be mo开发者_如何学Cre focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 6 years ago.

Improve this question

I want to separate a string with the occurrence of the Uppercase letters. Suppose I have an string like "IAmABoy".I want the resulting strings like

I
Am
A
Boy.

How to do this? Is there any sample code? Please show me the way to do this.


What about something simple like just iterating over each character? Assuming inputString and outputString are NSStrings something like this should work:

  NSUInteger length = [inputString length];
  for (NSUInteger i = 0; i < length; i++)
  {
    char c = [inputString characterAtIndex:i];
    if (i > 0 && c >= 65 && c <=90)
    {
      [outputString appendFormat:@"\n%c", c];
    }
    else
    {
      [outputString appendFormat:@"%c", c];
    }
  }


Thanx Carson for you reply.But the line

[outputString appendFormat:@"\n%c", c];

througing some exception.I have modify your code to the following one and it seems to be working for me.


NSString *inputString=@"IAmABoy"; NSString *outputString; NSString *string=@""; NSUInteger length = [inputString length]; for (NSUInteger i = 0; i < length; i++) { char c = [inputString characterAtIndex:i]; if (i > 0 && c >= 65 && c <=90) { //[outputString appandFormate:@"\n%c", c]; outputString=[NSString stringWithFormat:@"%c", c]; string = [NSString stringWithFormat:@"%@%@%@",string,@" ",outputString]; NSLog(@"%@", string); } else { //[outputString appendFormat:@"%c", c]; outputString=[NSString stringWithFormat:@"%c", c]; //NSLog(@"%@",outputString); string = [NSString stringWithFormat:@"%@%@",string,outputString]; NSLog(@"%@", string); } }


Thanx once again to all for your cooperations and help.


I'd suggest importing a Regex library or taking a look at NSScanner.


look into RegexKitLite


Try using -rangeOfCharacterFromSet: and splitting the string based on where you find the upper-case characters.


extension String { public func stringFromPascalCase() -> String { return self.characters.enumerate().map { (String($1).componentsSeparatedByCharactersInSet(.uppercaseLetterCharacterSet()).joinWithSeparator("").isEmpty && $0 > 0) ? " \($1)" : "\($1)" }.joinWithSeparator("") } }

this should do the trick.

let x = "EastMayerDrive".stringFromPascalCase() print(x) /// East Mayer Drive

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜