如何在iPhone上拆分字符串?

时间:2010-01-13 11:47:24

标签: iphone objective-c

我从服务器获得了以下值(动态):

drwxr-xr-x    9 0        0            4096 Jan 10 05:30 California

现在我想得到这样的价值。

drwxr-xr-x
9
0
0
4096
Jan 10
05:30 
California

请帮我解决这个问题

5 个答案:

答案 0 :(得分:8)

你可以尝试这样的smth

  

NSArray * components = [initialString componentsSeparatedByString:@“”];

答案 1 :(得分:4)

请参阅NSString componentsSeparatedByString获取答案。

答案 2 :(得分:2)

[myStringValue componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

也可能有用。

答案 3 :(得分:2)

正如其他人所提到的,您可以使用NSString's成员函数componentsSeparatedByString:componentsSeparatedByCharactersInSet:

作为替代方案(对于更强大的标记化),请查看Mac OS X基础框架中的Objective-C NSScanner类。

你可以这样做:

NSString *str = "drwxr-xr-x    9 0  ... ";
NSScanner *scanner = [NSScanner scannerWithString:str];

要以字符串形式获取每个令牌,请使用NSScanner's scanUpToCharactersFromSet:intoString:成员函数。

NSString *token = [NSString string];
NSCharacterSet *div = [NSCharacterSet whitespaceCharacterSet];
[scanner scanUpToCharactersFromSet:div intoString:token];
// token now contains @"drwxr-xr-x"

对上述内容的后续调用将返回9,0,依此类推。

注意:上面的代码尚未经过测试。

答案 4 :(得分:2)

使用正则表达式:RegexKitLite

这是一个使用正则表达式通过大量解释来执行所需操作的方法的“完整示例”,因此这是一个很长的答案。使用的正则表达式只是一种方法,它接受的是“相当宽容”。该示例显示:

  • 如何一次匹配多于“一行/目录”。
  • 处理不同日期格式(Jan 10 05:30Apr 30 2009
  • 的可能方式
  • 如何创建匹配的“数组数组”。
  • 迭代匹配的数组,并根据解析的结果创建NSDictionary
  • 创建结果的“逗号分隔值”版本。

注意:该示例将一些长字符串拆分为多行。 @"string1 " @"string2"形式的字符串文字将由编译器“自动”连接,以形成等同于@"string 1 string2"的字符串。我注意到这一点只是因为如果你不习惯它,这可能看起来有点不寻常。

#import <Foundation/Foundation.h>
#import "RegexKitLite.h"

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  NSString *stringToMatch = 
    @"drwxr-xr-x    9 0        0            4096 Jan 10 05:30 California\n"
    @"-rw-r--r--    1 johne  staff     1335 Apr 30  2009 tags.m"; // A random entry from my machine with an "older" date.

  NSString *regex =
    @"(?m)^" // (?m) means: to "have ^ and $ match new line boundaries".  ^ means: "Match the start of a line".
    // Below, 
    // (...) means: "Capture for extraction the matched characters".  Captures start at 1, capture 0 matches "everything the regex matched".
    // [^\\p{Z}]+ says: "Match one or more characters that are NOT 'Separator' characters (as defined by Unicode, essentially white-space)".
    // In essence, '[^\\p{Z}]+' matches "One or more non-white space characters."
    // \\s+ says: Match one or more white space characters.
    // ([^\\p{Z}]+)\\s+ means: Match, and capture, the non-white space characters, then "gobble up" the white-space characters after the match.
    @"([^\\p{Z}]+)\\s+" // Capture 1 - Permission
    @"([^\\p{Z}]+)\\s+" // Capture 2 - Links (per `man ls`)
    @"([^\\p{Z}]+)\\s+" // Capture 3 - User
    @"([^\\p{Z}]+)\\s+" // Capture 4 - Group
    @"([^\\p{Z}]+)\\s+" // Capture 5 - Size
    @"(\\w{1,3}\\s+\\d+\\s+(?:\\d+:\\d+|\\d+))\\s+" // Capture 6 - The "date" part.
    // \\w{1,3} means: One to three "word-like" characters (ie, Jan, Sep, etc).
    // \\d+ means: Match one or more "digit-like" characters.
    // (?:...) means: Group the following, but don't capture the results.
    // (?:.A.|.B.) (the '|') means: Match either A, or match B.
    // (?:\\d+:\\d+|\\d+) means: Match either '05:30' or '2009'.
    @"(.*)$"; // Capture 7 - Name. .* means: "Match zero or more of any character (except newlines).  $ means: Match the end of the line.

  // Use RegexKitLites -arrayOfCaptureComponentsMatchedByRegex to create an
  // "array of arrays" composed of:
  // an array of every match of the regex in stringToMatch, and for each match,
  // an array of all the captures specified in the regex.

  NSArray *allMatchesArray = [stringToMatch arrayOfCaptureComponentsMatchedByRegex:regex];

  NSLog(@"allMatchesArray: %@", allMatchesArray);

  // Here, we iterate over the "array of array" and create a NSDictionary
  // from the results.

  for(NSArray *lineArray in allMatchesArray) {
    NSDictionary *parsedDictionary =
      [NSDictionary dictionaryWithObjectsAndKeys:
      [lineArray objectAtIndex:1], @"permission",
      [lineArray objectAtIndex:2], @"links",
      [lineArray objectAtIndex:3], @"user",
      [lineArray objectAtIndex:4], @"group",
      [lineArray objectAtIndex:5], @"size",
      [lineArray objectAtIndex:6], @"date",
      [lineArray objectAtIndex:7], @"name",
      NULL];
    NSLog(@"parsedDictionary: %@", parsedDictionary);
  }

  // Here, we use RegexKitLites -stringByReplacingOccurrencesOfRegex method to
  // create a new string. We use it to essentially transform the original string
  // in to a "comma separated values" version of the string.
  // In the withString: argument, '$NUMBER' means: "The characters that were matched
  // by capture group NUMBER."

  NSString *commaSeparatedString = [stringToMatch stringByReplacingOccurrencesOfRegex:regex withString:@"$1,$2,$3,$4,$5,$6,$7"];
  NSLog(@"commaSeparatedString:\n%@", commaSeparatedString);

  [pool release];
  pool = NULL;
  return(0);
}

编译并运行:

shell% gcc -Wall -Wmost -arch i386 -g -o regexExample regexExample.m RegexKitLite.m -framework Foundation -licucore
shell% ./regexExample
2010-01-14 00:10:38.868 regexExample[49409:903] allMatchesArray: (
        (
        "drwxr-xr-x    9 0        0            4096 Jan 10 05:30 California",
        "drwxr-xr-x",
        9,
        0,
        0,
        4096,
        "Jan 10 05:30",
        California
    ),
        (
        "-rw-r--r--    1 johne  staff     1335 Apr 30  2009 tags.m",
        "-rw-r--r--",
        1,
        johne,
        staff,
        1335,
        "Apr 30  2009",
        "tags.m"
    )
)
2010-01-14 00:10:38.872 regexExample[49409:903] parsedDictionary: {
    date = "Jan 10 05:30";
    group = 0;
    links = 9;
    name = California;
    permission = "drwxr-xr-x";
    size = 4096;
    user = 0;
}
2010-01-14 00:10:38.873 regexExample[49409:903] parsedDictionary: {
    date = "Apr 30  2009";
    group = staff;
    links = 1;
    name = "tags.m";
    permission = "-rw-r--r--";
    size = 1335;
    user = johne;
}
2010-01-14 00:10:38.873 regexExample[49409:903] commaSeparatedString:
drwxr-xr-x,9,0,0,4096,Jan 10 05:30,California
-rw-r--r--,1,johne,staff,1335,Apr 30  2009,tags.m