【问题标题】:How split a string by equial parts?如何将字符串分成相等的部分?
【发布时间】:2014-08-23 19:03:15
【问题描述】:

如何将一个字符串分成相等的部分而不是一个字符,即一个由 20 个字符分成 5 个字符串的字符串,每个字符串有 2 个字符,不管是什么字符?

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

我在 xcode 5 上使用 objetive-c

【问题讨论】:

  • 现在5 * 2 = 20?至于问题:看看substringWithRange:.
  • 一个简单的循环和substringWithRange: ?只有在像 UTF-16 代理对这样的“组合字符序列”的情况下才会变得有趣(不要将表情符号切成两半:)
  • 执行此操作的确切方式会有所不同,具体取决于您想要做什么,是否要将每个字符串拆分为 5 个字符的块,是否要拆分固定长度的所有字符串?
  • jajaj 是的,很抱歉,我写得很快,但没有意识到 5 * 2 = jajaja 上的拼写错误

标签: objective-c split nsstring


【解决方案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 新测试[49723:60b] ( ab, 光盘, 英, 呃, ij, 吉隆坡, 锰, 操作, qr, st)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2015-05-30
    • 1970-01-01
    相关资源
    最近更新 更多