I have the following string:

R$1.234.567,89

I need it to look like: 1.234.567.89

How can i do this?

This is what i tried:

NSString* cleanedString = [myString stringByReplacingOccurrencesOfString:@"." withString:@""];
cleanedString = [[cleanedString stringByReplacingOccurrencesOfString:@"," withString:@"."]
                                     stringByTrimmingCharactersInSet: [NSCharacterSet symbolCharacterSet]];

It works, but I think there must be a better way. Suggestions?

有帮助吗?

解决方案

If your number always after $, but you got more characters before it, you can make it like this:

NSString* test = @"R$1.234.567,89";
NSString* test2 = @"TESTERR$1.234.567,89";
NSString* test3 = @"HEllo123344R$1.234.567,89";


NSLog(@"%@",[self makeCleanedText:test]);
NSLog(@"%@",[self makeCleanedText:test2]);
NSLog(@"%@",[self makeCleanedText:test3]);

method is:

- (NSString*) makeCleanedText:(NSString*) text{

    int indexFrom = 0;

    for (NSInteger charIdx=0; charIdx<[text length]; charIdx++)
        if ( '$' == [text characterAtIndex:charIdx])
            indexFrom = charIdx + 1;

    text = [text stringByReplacingOccurrencesOfString:@"," withString:@"."];
    return [text substringFromIndex:indexFrom];
}

result is:

2013-10-20 22:35:39.726 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.728 test[40546:60b] 1.234.567.89
2013-10-20 22:35:39.731 test[40546:60b] 1.234.567.89

其他提示

If you just want to remove the first two characters from your string you can do this

NSString *cleanedString = [myString substringFromIndex:2];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top