如何用相等的部分分割字符串?

时间:2014-08-23 19:03:15

标签: objective-c split nsstring

如何将字符串拆分成相等的部分而不是字符,即一个20个字符的字符串,分为5个字符串,每个字符不分2个字符?

对我不起作用[NSString componentsSeparatedByString]:因为字符会随机变化。

我在xcode 5上使用了objetive-c

1 个答案:

答案 0 :(得分:1)

这只是您可能想要做的一个例子。此方法假定字符串的长度可以被预期的子字符串长度整除,因此,如果测试字符串包含20个字符且子字符串长度为2,则将生成一个包含10个子字符串的数组,每个子字符串包含2个字符。 如果测试字符串为21个字符,则将忽略第21个字符 。再一次,这不是完成你想要做的事情的方式(这仍然不是完全清楚的),但它只是一个类似于你可能想要做的事情的演示:

// create our test substring (20 chars long)
NSString *testString = @"abcdefghijklmnopqrstu";

// our starting point will begin at 0
NSInteger startingPoint = 0;

// each substring will be 2 characters long
NSInteger substringLength = 2;

// create our empty mutable array
NSMutableArray *substringArray = [NSMutableArray array];

// loop through the array as many times as the substring length fits into the test
// string
for (NSInteger i = 0; i < testString.length / substringLength; i++) {
    // get the substring of the test string starting at the starting point, with the intended substring length
    NSString *substring = [testString substringWithRange:NSMakeRange(startingPoint, substringLength)];

    // add it to the array
    [substringArray addObject:substring];

    // increment the starting point by the amount of the substring length, so next iteration we
    // will start after the last character we left off at
    startingPoint += substringLength;
}

以上产生了这个:

  

2014-08-23 15:33:41.662 NewTesting [49723:60b](       AB,       光盘,       EF,       GH,       IJ,       KL,       MN,       OP,       QR,       st)