Is there a width in NSString?

I want to add my line with fixed-width spaces; For example, I want to show data in this format:

1 faizan 1 locked 10/20/2008 1 faizan 1 locked 10/20/2008 1 faizan 1 locked 10/20/2008 1 faizan 1 locked 10/20/2008 

But this only works with strings of the same length. If the lines are different as follows:

 1 faizan 1 locked 10/20/2008 2 faizanali 1 locked 10/20/2008 3 ali turab gilani 1 locked 10/20/2008 

then it does not fix the space. So that I can show data with the same number of spaces, I tried this:

 NSString *titleColumn = [[NSString stringWithFormat:@"%@:", title] stringByPaddingToLength:20 withString:@" " startingAtIndex:0]; serializedValue = [serializedValue stringByAppendingFormat:@"%@%@", titleColumn, value]; 

But that didn't work either. Does Objective-C have a function of type setwidth , as in C ++ and other languages?

+4
source share
2 answers

Do you do it that way?

/ * Define a helper method * /

 - (NSString *)formattedStringWithStrings:(NSArray *)strings { NSString *str1 = [[strings objectAtIndex:0] stringByPaddingToLength:3 withString:@" " startingAtIndex:0]; NSString *str2 = [[strings objectAtIndex:1] stringByPaddingToLength:20 withString:@" " startingAtIndex:0]; NSString *str3 = [[strings objectAtIndex:2] stringByPaddingToLength:3 withString:@" " startingAtIndex:0]; NSString *str4 = [[strings objectAtIndex:3] stringByPaddingToLength:10 withString:@" " startingAtIndex:0]; NSString *str5 = [[strings objectAtIndex:4] stringByPaddingToLength:15 withString:@" " startingAtIndex:0]; return [NSString stringWithFormat:@"%@%@%@%@%@", str1, str2, str3, str4, str5]; } 

/ * Use the helper method * /

 NSArray *strings = [NSArray arrayWithObjects:@"1", @"faizan", @"1", @"locked", @"10/20/2008", nil]; NSLog(@"%@", [self formattedStringWithStrings:strings]); strings = [NSArray arrayWithObjects:@"2", @"faizanali", @"1", @"locked", @"10/20/2008", nil]; NSLog(@"%@", [self formattedStringWithStrings:strings]); strings = [NSArray arrayWithObjects:@"3", @"ali turab gilani", @"1", @"locked", @"10/20/2008", nil]; NSLog(@"%@", [self formattedStringWithStrings:strings]); 

/ * And output * /

 1 faizan 1 locked 10/20/2008 2 faizanali 1 locked 10/20/2008 3 ali turab gilani 1 locked 10/20/2008 
+3
source

To implement this, you must use NSMutableString . The logic is this:

  • Check the maximum length string, say maxLength .
  • Now run the for loop to iterate over all the lines and add a line with a "" (space) if the current line length is less than maxLength .
  • Now with the final result, you get all the lines with the same length.
0
source

Source: https://habr.com/ru/post/1391977/


All Articles