我正在尝试将字符串写入文本文件。然后该文本文件将被另一个程序读取。第二个程序期望文本文件中的不同“字段”是固定宽度。因此,当我使用我的应用程序编写文本文件时,我需要在我的实际数据之间添加空格以使所有内容正确排列。如何添加这些空间?
到目前为止,我已经尝试编写一个将源字符串和目标长度作为输入的函数。如果目标比源长,它只是附加“”。此例程的代码如下:
- (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"); 运行多次。