不能缩短NSString长度

问题描述:

我想使这个程序,以便有一个小数的唯一时间是当小数是.5。我一直在尝试使用[string substringToIndex:[string length] - 2],但它什么也没做。是因为它不能附加浮点数?不能缩短NSString长度

float inchesInField = [sizeField.text floatValue]; 
float shoeSize = inchesInField * 3 - 22; 
NSMutableString *appendedShoeSize = [[NSMutableString alloc] 
              initWithFormat:@"%.1f", shoeSize]; 

if ([appendedShoeSize hasSuffix:@".3"] || [appendedShoeSize hasSuffix:@".5"] || 
    [appendedShoeSize hasSuffix:@".4"] || [appendedShoeSize hasSuffix:@".6"]) 
{ 
    [appendedShoeSize substringToIndex:[appendedShoeSize length] - 2]; 
    [appendedShoeSize appendString:@" ½"]; 
} 

if ([appendedShoeSize hasSuffix:@".0"] || [appendedShoeSize hasSuffix:@".1"] || 
    [appendedShoeSize hasSuffix:@".2"]) 
{ 
    [appendedShoeSize substringToIndex:[appendedShoeSize length] - 2]; 
} 

这是因为substringToIndex:NSString方法返回新的字符串,它不会修改原始字符串。 appendString:很好,但substringToIndex:是NSString的一种方法,所以它不会编辑原始字符串。

这应做到:

float inchesInField = [sizeField.text floatValue]; 
float shoeSize = inchesInField * 3 - 22; 
NSMutableString *appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%.1f", shoeSize]; 

if ([appendedShoeSize hasSuffix:@".3"] || [appendedShoeSize hasSuffix:@".5"] || [appendedShoeSize hasSuffix:@".4"] || [appendedShoeSize hasSuffix:@".6"]) { 

    appendedShoeSize = [[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2] mutableCopy]; 
    [appendedShoeSize appendString:@" ½"]; 
} 

if ([appendedShoeSize hasSuffix:@".0"] || [appendedShoeSize hasSuffix:@".1"] || [appendedShoeSize hasSuffix:@".2"]) { 

    appendedShoeSize = [[appendedShoeSize substringToIndex:[appendedShoeSize length] - 2] mutableCopy]; 
} 
+1

当然,我们可以在NSMutableString上使用'deleteCharactersInRange'来截断它。 – 2012-01-08 21:29:20

+0

这将是一个更一致的使用NSMutableString在这种情况下 – Daniel 2012-01-08 21:30:52

+0

当我尝试这个我得到了一个警告:“不兼容的指针类型分配给'NSMutableString * __强'从'NSString *' – AppleGuy 2012-01-08 21:36:15

当你调用substringToIndex :,它不会修改现有的字符串。它返回一个结果。你必须使用类似于: NSString * result = [attachedShoeSize substringToIndex:[attachedShoeSize length] - 2];

正如Daniel指出substringToIndex:返回一个新的字符串。

您应该使用replaceCharactersInRange:withString:,例如:

NSRange range; range.location = [appendedShoeSize length] - 2; range.length = 2; 
[appendedShoeSize replaceCharactersInRange:range withString:@" ½"] 

有关的NSMutableString方法的更多参考可在http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableString_Class/Reference/Reference.html

发现这不是一个答案,但替代,所有这些hasSuffix:的只是碎一点点。我想这你想要做什么:

float intpart; 
float fracpart = modff(shoeSize, &intpart); 
NSMutableString *appendedShoeSize; 

int size = (int)intpart; 
if (fracpart >= 0.3 && fracpart <= 0.6) 
    appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%d½", size]; 
else 
{ if (fracpart > 0.6) size += 1; 
    appendedShoeSize = [[NSMutableString alloc] initWithFormat:@"%d", size]; 
} 

modff分割一个浮动到它的分数(返回值)和整数(通过引用参数)部分。这段代码片段不需要可​​变字符串,但我留下了它,因为稍后您可能正在做其他事情。该片段还会使.7 - > .9变为下一个大小。