gpt4 book ai didi

objective-c - 无法缩短 NSString 长度

转载 作者:行者123 更新时间:2023-11-28 20:40:22 25 4
gpt4 key购买 nike

我试图让这个程序只有在小数为 .5 时才有小数。我一直在尝试使用 [string substringToIndex:[string length] - 2] 但它什么也没做。是因为它不能追加 float 吗?

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

最佳答案

因为 NSString 的 substringToIndex: 方法返回的是新字符串,并没有修改原字符串。 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];
}

关于objective-c - 无法缩短 NSString 长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8781462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com