1

我正在尝试将字符串写入文本文件。然后该文本文件将被另一个程序读取。第二个程序期望文本文件中的不同“字段”是固定宽度。因此,当我使用我的应用程序编写文本文件时,我需要在我的实际数据之间添加空格以使所有内容正确排列。如何添加这些空间?


到目前为止,我已经尝试编写一个将源字符串和目标长度作为输入的函数。如果目标比源长,它只是附加“”。此例程的代码如下:

- (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;
    }
}

这显然行不通。即使在 NSLog(@"hit"); 运行多次。

4

3 回答 3

4

有一种stringByPaddingToLength:withString:startingAtIndex:方法NSString可以做到这一点。

于 2013-04-11T14:21:41.487 回答
1

你想改变:

[newString stringByAppendingString:@" "];

进入:

newString = [newString stringByAppendingString:@" "];
于 2013-04-11T14:19:04.537 回答
1

你在这里犯了一个愚蠢的错误

 [newString stringByAppendingString:@" "];

将返回一个新字符串,并且不会影响调用者对象。你需要存储它

newString=[newString stringByAppendingString:@" "];

或者干脆

[newString appendString:@" "];
于 2013-04-11T14:18:13.927 回答