sscanf
是C函数库 <stdio.h>
中的一个函数, 主要用来从字符串读取格式化输入, 参考: https://www.runoob.com/cprogramming/c-function-sscanf.html
int sscanf(const char *str, const char *format, ...)
把 str 通过 format 格式化给后面的参数
#include <stdio.h>
int main(int argc, const char * argv[]) {
char *str = "0xf";
int value = 0;
// 把字符串str, 格式化赋值给 vaue, 格式化规则是: %X (%X是十六进制格式符, 0xf是16进制的f,对应十字制对应15)
sscanf(str, "%X", &value);
printf("%d\n", value); //15
return 0;
}
实际项目中的一个示例, RGB颜色转换:
#import <Foundation/Foundation.h>
NSUInteger hexStrToInt(NSString *str) {
uint32_t result = 0;
sscanf([str UTF8String], "%X", &result);
return result;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// NSString *rgb = @"FF0012";
NSLog(@"%lu", hexStrToInt(@"FF")); // 255
NSLog(@"%lu", hexStrToInt(@"00")); // 0
NSLog(@"%lu", hexStrToInt(@"12")); // 18
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int day, year;
char weekday[20], month[20], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
sscanf( dtm, "%s %s %d %d", weekday, month, &day, &year );
printf("%s %d, %d = %s\n", month, day, year, weekday ); // March 25, 1989 = Saturday
return(0);
}