【问题标题】:Multiline NSString with a character limit per line多行 NSString,每行有字符限制
【发布时间】:2015-05-11 06:16:35
【问题描述】:

我想构造一个多行 NSString(用于打印目的),每行有一个字符限制。每行最多应包含 25 个字符。行数可以是任何基于字符串的长度。 这是我的方法,我猜这不是最好的。在不手动检查字符串长度的情况下,最好的方法是什么?

NSString *strComment;
NSMutableString* strCustomerComments = [NSMutableString string];

if([strComment length]<=25){
   [strCustomerComments appendString:[NSString stringWithFormat:@"%@",strComment]];
}
else{
      [strCustomerComments appendString:[NSString stringWithFormat:@"%@\n%@",[[strComment substringToIndex:25],[strComment substringFromIndex:25]]];
   }  

【问题讨论】:

  • 字符串格式化步骤完全是多余的(您可以只使用description 以使您的代码更具可读性)。也使用下标符号代替objectAtIndex:objectForKey:
  • @TheParamagneticCroissant 对不起代码笨拙,我编辑了代码以提高可读性

标签: ios objective-c iphone nsstring


【解决方案1】:

我不知道它是否有用。这是您可以通过以下代码限制每行字符数的方法。

NSString* strTemp = @"Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.Welcome to the jannat and here you will get idea about what happend what you need my support so let start to figure out issue.+++++";

    NSMutableString* strNewString = [[NSMutableString alloc] init];

    NSInteger addExtra = 0;

    NSInteger noofFixedCharecterPerLine = 25;


    for (int i=0; i<([strTemp length]/noofFixedCharecterPerLine); i++) {

        NSInteger FixedLength = noofFixedCharecterPerLine;
        if (i==(([strTemp length]/noofFixedCharecterPerLine))-1) {

            FixedLength = [strTemp length]-1 - ((i*noofFixedCharecterPerLine)+addExtra);


        }

        NSRange range = NSMakeRange((i*noofFixedCharecterPerLine)+addExtra, FixedLength);

        NSString* subString = [strTemp substringWithRange:range];

        if (i!=0) {
            [strNewString appendFormat:@"\n%@",subString];
            addExtra++;
        }
        else{
            [strNewString appendFormat:@"%@",subString];
        }
    }

    NSLog(@"print : %@",strNewString);

希望这会对你有所帮助。

【讨论】:

  • @trojanfoe,我认为这是面糊选项。我还有另一种方法可以用特定数量的字符来限制 NSSting。但即使你可以使用 NSArray 来讲述 NSString。这也是数据存储机制。
  • @None 感谢您的回答。这解决了我的问题。顺便说一句,我们不能用 NSAttributes 做点什么吗?
  • @sajaz,感谢您的赞赏。我会查看它并让你知道。如果您满意,请点赞。
  • 我不明白它是如何被接受的答案,当它使用硬编码值时,甚至使用的逻辑都在跳过最后一行。
  • 各位,我测试了代码。它不会离开最后一行,而是每行的最后一个字符。但这足以让我微调代码并使用它。这就是为什么我将其标记为已接受的答案
【解决方案2】:

好的,这是一个(未经测试):

- (NSString *)splitString:(NSString *)string byWidth:(NSUInteger)width
{
    NSUInteger index = 0, length = [string length];
    NSMutableString *outString = [NSMutableString new];
    while (length > 0) {
        if ([outString length] > 0)
            [outString appendString:@"\n"];
        NSUInteger lineLen = MIN(length - index, width);
        [outString appendString:[string substringWithRange:NSMakeRange(index, lineLen)]];
        length -= lineLen;
        index += lineLen;
    }
    return outString;
}

【讨论】:

    【解决方案3】:

    我有一个非常快速的方法-(NSArray *)breakStringIntoParts:(NSString *)sentence noOfParts:(int )noOfParts,这肯定会有所帮助。

    这是代码的输出:-


    2015-05-11 13:04:25.120 vghnfgh[1011:15475] Line 1 Cntains 25 Characters i.e=I want to construct a mul
    2015-05-11 13:04:25.121 vghnfgh[1011:15475] Line 2 Cntains 25 Characters i.e=ti line NSString (for pri
    2015-05-11 13:04:25.122 vghnfgh[1011:15475] Line 3 Cntains 25 Characters i.e=nting purpose) with a cha
    2015-05-11 13:04:25.122 vghnfgh[1011:15475] Line 4 Cntains 25 Characters i.e=racter limit per line. Ea
    2015-05-11 13:04:25.122 vghnfgh[1011:15475] Line 5 Cntains 25 Characters i.e=ch line should have maxim
    2015-05-11 13:04:25.122 vghnfgh[1011:15475] Line 6 Cntains 25 Characters i.e=um of 25 characters. Numb
    2015-05-11 13:04:25.123 vghnfgh[1011:15475] Line 7 Cntains 25 Characters i.e=er of lines can be anythi
    2015-05-11 13:04:25.123 vghnfgh[1011:15475] Line 8 Cntains 25 Characters i.e=ng based on the length of
    2015-05-11 13:04:25.123 vghnfgh[1011:15475] Line 9 Cntains 25 Characters i.e= the string. This is my a
    2015-05-11 13:04:25.123 vghnfgh[1011:15475] Line 10 Cntains 25 Characters i.e=pproach which is not the 
    2015-05-11 13:04:25.123 vghnfgh[1011:15475] Line 11 Cntains 25 Characters i.e=best I guess. Whats is th
    2015-05-11 13:04:25.139 vghnfgh[1011:15475] Line 12 Cntains 25 Characters i.e=e best way to do this wit
    2015-05-11 13:04:25.139 vghnfgh[1011:15475] Line 13 Cntains 25 Characters i.e=hout manually checking th
    2015-05-11 13:04:25.140 vghnfgh[1011:15475] Line 14 Cntains 25 Characters i.e=e length of the string?
    

    代码如下:-

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        line=@"I want to construct a multi line NSString (for printing purpose) with a character limit per line. Each line should have maximum of 25 characters. Number of lines can be anything based on the length of the string. This is my approach which is not the best I guess. Whats is the best way to do this without manually checking the length of the string?";
    
        NSMutableArray *arrSentenceParts=[self breakStringIntoParts:line noOfParts:25];
    
    }
    
    -(NSArray *)breakStringIntoParts:(NSString *)sentence noOfParts:(int )noOfParts
    {
        NSMutableArray *arrResult=[[NSMutableArray alloc]init]; //to store character array each of 25 character long.
    
        NSMutableArray *range=[[NSMutableArray alloc]init];
    
        float rangeBreak =([sentence length] /noOfParts)+1; // this line divide how many objects will be there of 25 chars .
    
        for( int i=0;i<rangeBreak;i++)
        {
            [range addObject:[NSNumber numberWithInteger:i]]; // storing each range in an array;
    
        }
    
        NSInteger characterCount=0; // responsible for iterating the whole sentence
        for (int j=0; j < [range count]; j++) {  //looping and adding 25 characters in each range of arrResult
            NSMutableArray *characters = [[NSMutableArray alloc]init];
            for (NSInteger i=0; i < noOfParts; i++) {
                if(characterCount==[sentence length]) //stop the iteration on reaching last index of sentence
                {
                    break;
                }
                NSString *ichar  = [NSString stringWithFormat:@"%c", [sentence characterAtIndex:characterCount]];
                [characters addObject:ichar]; //storing each  character in character array
                characterCount++;
            }
            [arrResult addObject:characters]; //now add final character array in arrResult
        }
    
        NSMutableArray *strMergedArr=[[NSMutableArray alloc]init]; //will be storing   Array of strings
        for(int k=0;k<[arrResult count];k++)
        {
            NSString *resultString = [[arrResult objectAtIndex:k] componentsJoinedByString:@""]; //merging all the characters in specific index of arrResult and storing in NSString
    
            [strMergedArr addObject:resultString]; // adding one by one in Merged Array of Strings
             NSLog(@"Line %d Cntains 25 Characters i.e=%@",k+1,[strMergedArr objectAtIndex:k]); // demo purpose can be commented
    
        }
    
        return strMergedArr; // finally returning the Array of Strings , and each string length 25 Charcters .
    
    
    }
    

    【讨论】:

    • @trojanfoe 感谢您的评论,我稍后添加了 cmets 以便更好地理解。但是要理解代码及其功能,必须具有分析能力并需要一点智能,这似乎有些用户没有没有。
    • @trojanfoe [sentence characterAtIndex:characterCount] 用于存储在 NSString 中,因为我们不能直接将 unichar 数据类型作为对象添加到 NSMutableArray 中。
    • 你为什么首先处理字符,而不是子字符串?
    • 因为这是所使用的逻辑所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多