如何在 Objective-C 中进行字符串转换?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/169925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 20:48:00  来源:igfitidea点击:

How to do string conversions in Objective-C?

objective-ccocoacocoa-touch

提问by rksprst

I want to convert a string into a double and after doing some math on it, convert it back to a string.

我想将字符串转换为双精度值,然后对其进行一些数学运算,然后将其转换回字符串。

How do I do this in Objective-C?

我如何在 Objective-C 中做到这一点?

Is there a way to round a double to the nearest integer too?

有没有办法将双精度舍入到最接近的整数?

回答by olliej

You can convert an NSString into a double with

您可以将 NSString 转换为 double

double myDouble = [myString doubleValue];

Rounding to the nearest int can then be done as

然后可以四舍五入到最近的 int

int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

I'm honestly not sure if there's a more streamlined way to convert back into a string than

老实说,我不确定是否有比转换回字符串更简化的方法

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

回答by Chris Hanson

To really convert from a string to a number properly, you need to use an instance of NSNumberFormatterconfigured for the locale from which you're reading the string.

要真正正确地从字符串转换为数字,您需要使用NSNumberFormatter为读取字符串的语言环境配置的实例。

Different locales will format numbers differently. For example, in some parts of the world, COMMAis used as a decimal separator while in others it is PERIOD—?and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.

不同的语言环境会以不同的方式格式化数字。例如,在世界的某些地方,COMMA用作小数分隔符,而在其他地方则PERIOD用作 -? 并且千位分隔符(使用时)被反转。除非是空格。或者根本不存在。

It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatterfor the way your input is formatted and use -[NSFormatter numberFromString:]to get an NSNumberfrom it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:]instead.

这实际上取决于输入的出处。最安全的做法是NSNumberFormatter为输入的格式配置 an并用于-[NSFormatter numberFromString:]从中获取 an NSNumber。如果要处理转换错误,可以-[NSFormatter getObjectValue:forString:range:error:]改用。

回答by Barry Wark

Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:

添加到 olliej 的答案中,您可以从 int 转换回带有NSNumber's的字符串stringValue

[[NSNumber numberWithInt:myInt] stringValue]

stringValueon an NSNumberinvokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt]will give you a properly localized reprsentation of myInt.

stringValueNSNumberinvokes 上descriptionWithLocale:nil,为您提供本地化的字符串表示值。我不确定是否[NSString stringWithFormat:@"%d",myInt]会给你一个正确本地化的myInt.

回答by Paul Dixon

olliej's roundingmethod is wrong for negative numbers

olliej 的舍入方法对于负数是错误的

  • 2.4 rounded is 2 (olliej's method gets this right)
  • ?2.4 rounded is ?2 (olliej's method returns -1)
  • 2.4 四舍五入是 2(olliej 的方法是正确的)
  • ?2.4 四舍五入是?2(olliej 的方法返回-1)

Here's an alternative

这是一个替代方案

  int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))

You could of course use a rounding function from math.h

您当然可以使用 math.h 中的舍入函数

回答by miker

Here's a working sample of NSNumberFormatter reading localized number String (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks such as "8,765.4 ", this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)

这是 NSNumberFormatter 读取本地化数字字符串(xCode 3.2.4,osX 10.6)的工作示例,以节省其他人我刚刚花费的时间。注意:虽然它可以处理诸如“8,765.4”之类的尾随空白,但它不能处理前导空格,也不能处理杂散文本字符。(错误的输入字符串:“8”和“8q”和“8q”。)

NSString *tempStr = @"8,765.4";  
     // localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
     // next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial

NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(@"string '%@' gives NSNumber '%@' with intValue '%i'", 
    tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release];  // good citizen

回答by Samir Jwarchan

// Converting String in to Double

double doubleValue = [yourString doubleValue];

// Converting Double in to String
NSString *yourString = [NSString stringWithFormat:@"%.20f", doubleValue];
// .20f takes the value up to 20 position after decimal

// Converting double to int

int intValue = (int) doubleValue;
or
int intValue = [yourString intValue];

回答by Robert

For conversion from a number to a string, how about using the new literals syntax (XCode >= 4.4), its a little more compact.

对于从数字到字符串的转换,如何使用新的文字语法(XCode >= 4.4),它更紧凑一些。

int myInt = (int)round( [@"1.6" floatValue] );

NSString* myString = [@(myInt) description];

(Boxes it up as a NSNumberand converts to a string using the NSObjects' description method)

(将其装箱NSNumber并使用NSObjects 的描述方法转换为字符串)

回答by benzado

For rounding, you should probably use the C functions defined in math.h.

对于四舍五入,您可能应该使用 math.h 中定义的 C 函数。

int roundedX = round(x);

Hold down Option and double click on roundin Xcode and it will show you the man page with various functions for rounding different types.

按住 Option 并round在 Xcode 中双击它,它将向您显示具有各种功能的手册页,用于舍入不同类型。

回答by Sam Soffes

This is the easiest way I know of:

这是我所知道的最简单的方法:

float myFloat = 5.3;
NSInteger myInt = (NSInteger)myFloat;

回答by zoltan

from this example here, you can see the the conversions both ways:

从这里的这个例子,你可以看到两种方式的转换:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);