如何将一个NSString从CamelCase转换为TitleCase,'playerName'转换为'Player Name'?

时间:2011-01-04 00:39:47

标签: objective-c string cocoa camelcasing

我正在寻找将字符串从驼峰格式转换为标题大小写格式的最简单方法。

如何将'playerName'更改为'玩家名'?

16 个答案:

答案 0 :(得分:21)

NSString *str = @"playerName";
NSMutableString *str2 = [NSMutableString string];

for (NSInteger i=0; i<str.length; i++){
    NSString *ch = [str substringWithRange:NSMakeRange(i, 1)];
    if ([ch rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]].location != NSNotFound) {
        [str2 appendString:@" "];
    }
    [str2 appendString:ch];
}
NSLog(@"%@", str2.capitalizedString);

答案 1 :(得分:15)

这是一个更简单的Swift版本。我把它扔进了一个扩展名

extension String {

    func stringFromCamelCase() -> String {
        var string = self
        string = string.stringByReplacingOccurrencesOfString("([a-z])([A-Z])", withString: "$1 $2", options: NSStringCompareOptions.RegularExpressionSearch, range: Range<String.Index>(start: string.startIndex, end: string.endIndex))
        string.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
        return string
    }

}

用法:

var str = "helloWorld"
str = str.stringFromCamelCase()

答案 2 :(得分:11)

尝试使用正则表达式替换

NSString *modified = [input stringByReplacingOccurrencesOfString:@"([a-z])([A-Z])"
                                                      withString:@"$1 $2"
                                                         options:NSRegularExpressionSearch
                                                           range:NSMakeRange(0, input.length)];

答案 3 :(得分:5)

稍微短一些,使用NSCharacterSet:

__block NSString *str = @"myVerySpecialPlayerName" ;

// split at uppercase letters
NSArray *splitString = [str componentsSeparatedByCharactersInSet:
     [NSCharacterSet uppercaseLetterCharacterSet]] ;

// get the uppercase letters
NSArray *upperCaseLetters = [str componentsSeparatedByCharactersInSet:
     [[NSCharacterSet uppercaseLetterCharacterSet] invertedSet]] ;

// join with two spaces
str = [splitString componentsJoinedByString:@"  "] ;
__block NSInteger offset = 0 ;

// replace each second space with the missing uppercase letter
[upperCaseLetters enumerateObjectsUsingBlock:^(NSString *character, NSUInteger idx, BOOL *stop) {
    if( [character length] > 0 ) {
        str = [str stringByReplacingCharactersInRange:NSMakeRange(idx+offset+1, 1) withString:character] ;
        offset += 2 ;
    }
}] ;

// & capitalize the first one
str = [str capitalizedString] ;

NSLog(@"%@", str) ; // "My Very Special Player Name"

答案 4 :(得分:2)

我认为你可以使用一些正则表达式解决这个问题。看看这个类似的问题:iPhone dev: Replace uppercase characters in NSString with space and downcase

答案 5 :(得分:2)

虽然有点长,但NSString的这个类别应该可以解决问题。它通过了我所有的测试:

- (NSString *)splitOnCapital
{
  // Make a index of uppercase characters
  NSRange upcaseRange = NSMakeRange('A', 26);
  NSIndexSet *upcaseSet = [NSIndexSet indexSetWithIndexesInRange:upcaseRange];

  // Split our camecase word
  NSMutableString *result = [NSMutableString string];
  NSMutableString *oneWord = [NSMutableString string];
  for (int i = 0; i < self.length; i++) {
    char oneChar = [self characterAtIndex:i];
    if ([upcaseSet containsIndex:oneChar]) {
      // Found a uppercase char, now save previous word
      if (result.length == 0) {
        // First word, no space in beginning
        [result appendFormat:@"%@", [oneWord capitalizedString]];
      }else {
        [result appendFormat:@" %@", oneWord];
      }

      // Clear previous word for new word
      oneWord = [NSMutableString string];
    }

    [oneWord appendFormat:@"%c", oneChar];
  }

  // Add last word
  if (oneWord.length > 0) {
    [result appendFormat:@" %@", oneWord];
  }

  return result;
}

答案 6 :(得分:2)

我有类似的问题,这里的答案帮助我创建了一个解决方案。我有一个数组,其中包含我想在UITableView中显示的标签列表,每行一个标签。

我的问题是我用SOAP操作返回的XML解析了这些标签,我不知道字符串的格式。

首先,我将webstersx的答案实施到一个方法中。这很棒,但是这些标签中的一些以大写字母开头,一些以驼峰形式开头(例如某些字符串exampleLabel而其他字符串ExampleLabel。所以这意味着以大写字母开头的那些字母已插入空格在字符串前面。

我通过使用NSString的stringByTrimmingCharactersInSet修剪字符串的开头和结尾处的空格来克服这个问题。

下一个问题是使用的任何缩写,例如“ID”或“PNR状态”,其中显示为“ID”和“PNR状态”作为大写字母,并且非常正确地被拾取和空格插在它之前。

我通过在我的新方法中实现类似于emdog4的回答的正则表达式克服了这个问题。

这是我完成的解决方案:

- (NSString *)formatLabel:(NSString *)label
{
    NSMutableString *str2 = [NSMutableString string];

    for (NSInteger i=0; i<label.length; i++){
        NSString *ch = [label substringWithRange:NSMakeRange(i, 1)];
        if ([ch rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]].location != NSNotFound) {
            [str2 appendString:@" "];
        }
        [str2 appendString:ch];
    }
    NSString * formattedString = [str2 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].capitalizedString;

    formattedString = [formattedString stringByReplacingOccurrencesOfString:@"([A-Z]) (?![A-Z][a-z])" withString:@"$1" options:NSRegularExpressionSearch range:NSMakeRange(0, formattedString.length)];

    return formattedString;
}
然后我会简单地调用这样的东西,例如,它会返回格式很好的字符串:

NSString * formattedLabel = [self formatLabel:@"PNRStatus"];
NSLog(@"Formatted Label: %@", formattedLabel);

将输出:

2013-10-10 10:44:39.888测试项目[28296:a0b]格式化标签:PNR状态

答案 7 :(得分:2)

如果有人需要Swift版本:

func camelCaseToTitleCase(s: NSString) -> String {
    var newString = ""
    if s.length > 0 {
        newString = s.substringToIndex(1).uppercaseString
        for i in 1..<s.length {
            let char = s.characterAtIndex(i)
            if NSCharacterSet.uppercaseLetterCharacterSet().characterIsMember(char) {
                newString += " "
            }
            newString += s.substringWithRange(NSRange(location: i, length: 1))
        }
    }
    return newString
}

答案 8 :(得分:2)

尝试更符合unicode

extension String {
    func camelCaseToTitleCase() -> String {
        return unicodeScalars.map(replaceCaptialsWithSpacePlusCapital).joined().capitalized
    }
    private func replaceCaptialsWithSpacePlusCapital(unichar: UnicodeScalar) -> String {
        if CharacterSet.uppercaseLetters.contains(unichar) {
            return " \(unichar)"
        }
        return "\(unichar)"
    }
}

答案 9 :(得分:1)

虽然技术上更短,更无效

NSString *challengeString = @"playerName";
NSMutableString *rStr = [NSMutableString stringWithString:challengeString];

while ([rStr rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]].location != NSNotFound) {
    [rStr replaceCharactersInRange:[rStr rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]] withString:[[NSString stringWithFormat:@" %@", [rStr substringWithRange:[rStr rangeOfCharacterFromSet:[NSCharacterSet uppercaseLetterCharacterSet]]]] lowercaseString]];
}

NSLog(@"%@", rStr.capitalizedString);

答案 10 :(得分:1)

不确定这比websterx短得多,但我发现使用characterIsMember更容易阅读和理解。如果字符串以大写字母开头,还添加了一个长度检查来修复空格。

NSString *str = @"PlayerNameHowAboutALongerString";
NSMutableString *str2 = [NSMutableString string];

for (NSInteger i=0; i<str.length; i++){
    unichar ch = [str characterAtIndex:i];
    if ( [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:ch]) {
        if (str2.length > 0 ) {
            [str2 appendString:@" "];
        }
    }
    [str2 appendString:[NSString stringWithCharacters:&ch length:1]];
}
NSLog(@"--%@--", str2.capitalizedString);

答案 11 :(得分:1)

接受的答案对我不起作用,因为它没有把第一个字母大写,如果第一个字母已经大写,它会在开头添加一个无关的空格。这是我的改进版本:

- (NSString *)titleFromCamelCaseString:(NSString *)input
{
    NSMutableString *output = [NSMutableString string];
    [output appendString:[[input substringToIndex:1] uppercaseString]];
    for (NSUInteger i = 1; i < [input length]; i++)
    {
        unichar character = [input characterAtIndex:i];
        if ([[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:character])
        {
            [output appendString:@" "];
        }
        [output appendFormat:@"%C", character];
    }
    return output;
}

答案 12 :(得分:0)

这是Swift Code(webstersx的目标c代码),谢谢!

var str: NSMutableString = "iLoveSwiftCode"

        var str2: NSMutableString = NSMutableString()

        for var i:NSInteger = 0 ; i < str.length ; i++ {

            var ch:NSString = str.substringWithRange(NSMakeRange(i, 1))
            if(ch .rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()).location != NSNotFound) {
            str2 .appendString(" ")
            }
            str2 .appendString(ch)
        }
        println("\(str2.capitalizedString)")

    }

答案 13 :(得分:0)

    .page img {
        max-width: 300px;
    }

    .keepoffa img, .keepoffb img {
        max-width: initial;
    }

答案 14 :(得分:0)

Swift 2.2下的另一个解决方案

extension String {
    var stringFromCamelCase:String {
        return (self as NSString).replacingOccurrences(
            of: "([a-z])([A-Z])",
            with: "$1 $2",
            options: CompareOptions.regularExpressionSearch,
            range: NSMakeRange(0, self.characters.count)
            ).uppercaseFirst
    }

    var uppercaseFirst: String {
        return String(characters.prefix(1)).uppercased() + String(characters.dropFirst()).lowercased()
    }
}

答案 15 :(得分:-8)

尝试使用:

string.Split()

然后使用上限字母作为标记