Pregunta

I'm trying to write a string to a text file. That text file will then be read by another program. That second program is expecting the different "fields" in the text file to be a fixed width. Therefore, when I write the text file with my app, I will need to add spaces between my actual data to get everything to line up correctly. How do I get these spaces added?


So far, I've tried writing a function that takes a source string and a target length as input. If the target is longer than the source, it just appends " ". Code for this routine is below:

- (NSString *) makeStringFrom:(NSString *)source withLength:(NSInteger)length
{
    // Method to add spaces to the end of a string to get it to a certain length
    if ([source length] > length)
    {
        // String is too long - throw warning and send it back
        NSLog(@"Warning - string is already longer than length supplied.  Returning source string");
        return source;
    }
    else if ([source length] == length)
    {
        // String is already correct length, so just send it back
        return source;
    }
    else
    {
        // String is too short, need to add spaces
        NSMutableString *newString = [[NSMutableString alloc] initWithString:source];
        NSLog(@"newString initial length = %d",[newString length]);
        for (int current = [source length]; current < length; current ++)
        {
            [newString stringByAppendingString:@" "];
            NSLog(@"hit");
        }

        NSLog(@"target length = %d.  newString length = %d",length,[newString length]);
        return newString;
    }
}

This apparently doesn't work. The length of the string I'm getting back in the return isn't changing any from the length of the supplied string, even when the NSLog(@"hit"); runs multiple times.

¿Fue útil?

Solución

There's a stringByPaddingToLength:withString:startingAtIndex: method on NSString that does just this.

Otros consejos

You did a silly mistake here

 [newString stringByAppendingString:@" "];

This returns a new string, and it doesnot effect the caller object. You need to store it

newString=[newString stringByAppendingString:@" "];

or simply

[newString appendString:@" "];

You want to change:

[newString stringByAppendingString:@" "];

into:

newString = [newString stringByAppendingString:@" "];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top