Fixed Length String??

Discussion in 'Mac Programming' started by Fritzables, Mar 27, 2012.

  1. macrumors regular

    I am having trouble working out how to create a fixed length string.

    I have a need to create a NSString that has a maximum number of characters of 12.

    If I assign a sting that has 6 characters then the balance of the would need to be 6 blank spaces for example.

    Is this at all possible or will it always be trimmed.

  2. macrumors 68030


    Perhaps thing somewhat backwards. What if you started with a 12 space NSString and then replaced a portion of it with your possibly less than 12 space string.
  3. macrumors regular

    G'Day Jared,

    I will give it a try and see what comes out the other end.
  4. macrumors regular

    Well.... I managed to find something that works for me. I used a variation of:

    NSString *mycall = [NSString stringWithFormat:@"%@",[stnCallSign stringValue]];
    mycall = [mycall stringByPaddingToLength:12 withString:@" " startingAtIndex:0];

  5. macrumors 68030


    I guess thats one way to do it. I was thinking something like this. The NSString class never ceases to amaze!

    NSString *blanks = @"            ";
    NSString *insert = @"test";
    NSString *out = [blanks stringByReplacingCharactersInRange: NSMakeRange( 0, [insert length]) withString: insert];
    With appropriate boundary conditions to ensure that insert wasn't longer than blanks, etc...

    Why would you go through this trouble instead of just..
    NSString *mycall = [stnCallSign retain];
    or just..
    NSString *mycall = [stnCallSign stringByPaddingToLength:12 withString:@" " startingAtIndex:0];
  6. macrumors 603

    stnCallSign probably isn't an NSString. Note the use of stringValue in the OP code. This is not an NSString method AFAIK.

    Also, retain is unbalanced, so that's a leak.

    You probably meant something more like this:
    NSString *mycall = [stnCallSign stringValue];
    or this:
    NSString *mycall = [[stnCallSign stringValue] stringByPaddingToLength:12 withString:@" " startingAtIndex:0];
    But I do agree with you that the senseless use of stringWithFormat: should be burned with fire. Because the short analysis of the problem is: "It's already an NSString".
  7. macrumors 68030


    Yeah, obviously I meant the interim -(NSString *)stringValue;
    And I certainly didn't mean to unbalance a retain, I just meant for him to think about ownership, like -retain or -copy instead of +stringWithFormat:;

Share This Page