[英]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). 在我的Objective-C代码中,我想获取一个NSString值,对字母进行迭代,对字母的ASCII值求和并将其返回给用户(最好也是NSString)。
I have already written a loop, but I don't know how to get the ASCII value of an individual character. 我已经编写了一个循环,但是我不知道如何获取单个字符的ASCII值。 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. 注意:我见过类似的问题,这些问题与获取ASCII值有关,但是所有这些问题最终都将值显示为字符串。 I still don't know how to get ASCII value as NSInteger.
我仍然不知道如何获取NSInteger的ASCII值。
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? 谢谢您如何使用ASCII值的总和将NSString转换为NSInteger? 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! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.