我想写一个字符串到文本文件。该文本文件将被另一个程序读取。第二个程序期望文本文件中的不同“字段”为固定宽度。因此,当我使用我的应用程序编写文本文件时,我需要在我的实际数据之间添加空格以使所有内容正确排列。我如何获得这些空间?如何使用NSMutableString将字符串填充到固定宽度?
到目前为止,我已经尝试写一个函数,接受源字符串和目标长度作为输入。如果目标比源更长,它只会追加“”。此例程代码如下:
- (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”);}时,返回的字符串的长度也不会改变所提供的字符串的长度。运行多次。
'for(int i = 0; i
2013-04-11 14:14:01
@AnoopVaidya:这就是我所尝试的(请参阅下面的答案)。我做错什么了吗? – GeneralMike 2013-04-11 14:16:16
不,你没有做同样的:) – 2013-04-11 14:21:39