Objective-C - 如何从字符串中删除字符? [英] Objective-C - How To Remove Characters From a String?

查看:182
本文介绍了Objective-C - 如何从字符串中删除字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UILabel,它有一个格式化的字符串(格式为货币),所以有一个美元符号,$ 21.34。



在核心数据实体中,属性的类型是double,我使用NSDecimalNumber来保存到数据库中。

  self.purchase.name = self.nameTextField.text; 
NSString * string = self.amountLabel.text
NSDecimalNumber * newAmount = [[NSDecimalNumber alloc] initWithString:string];
NSLog(@%@,string); //这个返回NaN,因为美元符号我想

NSManagedObjectContext * context = self.purchase.managedObjectContext;

NSError * error = nil;
if(![context save:& error])
{
NSLog(@Unresolved error%@,%@,error,[error userInfo]);
abort();





$ b无论如何,我需要这个不是NaN,所以我的想法是去除美元符号,但我不知道该怎么做,或者有更好的方法来实现我的目标。

解决方案

  NSString * clearedString = [costString stringByTrimmingCharactersInSet:[NSCharacterSet symbolCharacterSet]]; 

比上面的更强大(我想它也会处理逗号) / p>

I have a UILabel that has a formatted String (formatted for currency), so there is a dollar sign, $21.34.

In the core data entity the attribute is of a type double, I am using an NSDecimalNumber to save to the database.

    self.purchase.name = self.nameTextField.text;
    NSString *string = self.amountLabel.text
    NSDecimalNumber *newAmount = [[NSDecimalNumber alloc] initWithString:string];
    NSLog(@"%@", string); // THIS RETURNS NaN, because of dollar sign i think

    NSManagedObjectContext *context = self.purchase.managedObjectContext;

    NSError *error = nil;
    if (![context save:&error]) 
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

Anyway, I need this to not be NaN, so my thinking is to remove the dollar sign, but i do not know how to do that, or perhaps there is a better way to accomplish my goal.

解决方案

    NSString* cleanedString = [costString stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]];

Is a lot more robust than the one above (and I think it will handle commas, too)

这篇关于Objective-C - 如何从字符串中删除字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆