如何获得“\ n”字符后的值?

时间:2011-06-04 02:30:40

标签: objective-c cocoa-touch ios nsstring newline

我希望从字符串中获取换行符\n之后的所有值。我怎样才能获得这些价值观?

3 个答案:

答案 0 :(得分:8)

试试这个:

NSString *substring = nil;
NSRange newlineRange = [yourString rangeOfString:@"\n"];
if(newlineRange.location != NSNotFound) {
  substring = [yourString substringFromIndex:newlineRange.location];
}

答案 1 :(得分:1)

查看方法componentsSeparatedByString here

参考文献中的一个简单示例:

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];

这将生成一个NSArray,其中的字符串分隔为:{ @"Norman", @"Stanley", @"Fletcher" }

答案 2 :(得分:0)

这是类似的函数,它通过分隔符拆分字符串,并返回带有两个修剪值的数组。

NSArray* splitStrByDelimAndTrim(NSString *string, NSString *delim)
{
    NSRange range = [string rangeOfString: delim];

    NSString *first;
    NSString *second;

    if(range.location == NSNotFound)
    {
        first = @"";
        second = string;
    }
    else
    {
        first = [string substringToIndex: range.location];
        first = [first stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
        second = [string substringFromIndex: range.location + 1];
        second = [second stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
    }

    return [NSArray arrayWithObjects: first, second, nil];
}