简体   繁体   中英

How to convert a NSString to NSInteger with the sum of ASCII values?

In my Objective-C code I'd like to take a NSString value, iterate through the letters, sum ASCII values of the letters and return that to the user (preferably as the NSString too).

I have already written a loop, but I don't know how to get the ASCII value of an individual character. What am I missing?

- (NSString*) getAsciiSum: (NSString*) input {                                                      
    NSInteger sum = 0;                                                                      
    for (NSInteger index=0; index<input.length; index++) {                                  
        sum = sum + (NSInteger)[input characterAtIndex:index];                          
    }                                                                                       
    return [NSString stringWithFormat: @"%@", sum];                                         
}

Note: I've seen similar questions related to obtaining ASCII values, but all of them ended up displaying the value as a string. I still don't know how to get ASCII value as NSInteger.

This should work.

- (NSInteger)getAsciiSum:(NSString *)stringToSum {
    int asciiSum = 0;
    for (int i = 0; i < stringToSum.length; i++) {
        NSString *character = [stringToSum substringWithRange:NSMakeRange(i, 1)];
        int asciiValue = [character characterAtIndex:0];
        asciiSum = asciiSum + asciiValue;
    }
    return asciiSum;
}

Thank you to How to convert a NSString to NSInteger with the sum of ASCII values? for the reference.

Here is the answer:

- (NSString *) getAsciiSum: (NSString *) input
{
    NSString *input = @"hi";
    int sum = 0;
    for (NSInteger index = 0; index < input.length; index++)
    {
        char c = [input characterAtIndex:index];

        sum = sum + c;
    }

    return [NSString stringWithFormat: @"%d", sum]);
}

This is working for me.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM