C/C++/Qt中的字符串常用操作
- 字符串操作:查找、截取、拼接、数值转换
- 本文限制在
C/C++11
标准及以下
C中的字符串操作
- C中的字符串通常是 char* 类型的字符串数组类型
- 一般使用
sprintf
做字符串拼接、转换
- 输出使用
printf
控制
- 空终止字节字符串
查找、截取
void ipv4ToUint32_c(char *ip_str, uint32_t &ip_int)
{
char *token = strtok(ip_str, ".");
while (token)
{
ip_uint <<= 8;
ip_uint += strtoul(token, NULL, 10);
token = strtok(NULL, ".");
}
}
替换
拼接、格式化
static void uint32ToIpv4_c(uint32_t ip_i, char *c)
{
snprintf(c, 16, "%d.%d.%d.%d", (uint8_t)(ip_i >> 24), (uint8_t)(ip_i >> 16), (uint8_t)(ip_i >> 8), (uint8_t)ip_i);
}
数值转换
字符串转数值
#include <errno.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *p = "10 200000000000000000000000000000 30 -40 junk";
printf("Parsing '%s':\n", p);
for (;;)
{
errno = 0;
char *end;
const long i = strtol(p, &end, 10);
if (p == end)
break;
const bool range_error = errno == ERANGE;
printf("Extracted '%.*s', strtol returned %ld.", (int)(end-p), p, i);
p = end;
if (range_error)
printf(" Range error occurred.");
putchar('\n');
}
printf("Unextracted leftover: '%s'\n\n", p);
printf("\"1010\" in binary --> %ld\n", strtol("1010", NULL, 2));
printf("\"12\" in octal --> %ld\n"