ios - 将字符串拆分为 Objective-C 中的内容页面

标签 ios arrays nsstring split

我正在尝试将一个相当长的字符串的内容拆分为内容页面。现在我按字符(每页 500 个字符)这样做:

//Lets find out how many pages to make
    int pageLength = 500; //how many characters per page
    NSString *text = ((Story *) [self.story objectAtIndex:chapter]).content;
    int NumberOfPages = (text.length/pageLength);
    //NumberOfPages += 1;

    //Build the Pages Array
    NSMutableArray *pageStrings = [[NSMutableArray alloc] init];
    for (int i = 0; i <= (NumberOfPages+1); i++)
    {
        if (i < NumberOfPages) {
            //Load the text like normal
            NSString *contentString = [[NSString alloc]initWithFormat:@"<html><head><style type=text/css>body {font-family: \"%@\"; font-size: %d;}</style></head><body><p>%@</p></body></htlm>",@"helvetica",20,[text substringWithRange:NSMakeRange(i*pageLength,pageLength)]];
            [pageStrings addObject:contentString];
        }
        if (i == NumberOfPages) {
            //on the last page, only load what's available
            NSString *contentString = [[NSString alloc]initWithFormat:@"<html><head><style type=text/css>body {font-family: \"%@\"; font-size: %d;}</style></head><body><p>%@</p></body></htlm>",@"helvetica",20,[text substringWithRange:NSMakeRange(i*pageLength,(text.length-(i*pageLength)))]];
            [pageStrings addObject:contentString];
        }
        if (i > NumberOfPages){
            //add in a blank page on the end
            NSString *contentString = [[NSString alloc]initWithFormat:@"<html><head><style type=text/css>body {font-family: \"%@\"; font-size: %d;}</style></head><body><p>%@</p></body></htlm>",@"helvetica",20,@"What do you do?"];
            [pageStrings addObject:contentString];
        }
    }
    pageContent = [[NSArray alloc] initWithArray:pageStrings];

这很好用,但通常会以单词在中间分开而告终。我试图让它在这个词上 split 。该字符串不必正好是 500 个字符,只需接近它即可。

最佳答案

如果你想“正确”地做到这一点,你应该看看 NSString 方法:

- (void)enumerateSubstringsInRange:(NSRange)range options:(NSStringEnumerationOptions)opts usingBlock:(void (^)(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop))block

您可以按单词、行、段落、句子和字符序列智能地枚举文本。

Session 128,WWDC 2011,“高级文本处理”对此有一些很好的信息。

关于ios - 将字符串拆分为 Objective-C 中的内容页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12046816/

相关文章:

iphone - 关于数据模型的思考

ios - 即使条件完成后,For 循环仍会迭代解析 JSON

objective-c - 如何在 iphone sdk 中将 NSString 转换为 UTF-8 格式的字符串?

objective-c - 从 NSString 中删除标记字符

ios - 如何在 Parse.com 中使用 Sql "Select"for Swift

ios - fatal error : unexpectedly found nil while unwrapping an Optional value - Core Data (Swift)

Java - 从文本文件创建二维数组时遇到问题

ios - 如何确定NSString是否全部大写

javascript - PHP 获取对象键

Python:将 2D numpy 数组转换为字典