C语言中完美的解决分离字符串“stock”、“sscanf”

本文详细介绍了使用C语言进行字符串处理的方法,包括如何利用strtok函数以特定分隔符分割字符串,以及通过sscanf函数解析复杂的数据格式。通过具体代码示例,读者可以学习到高效处理字符串的实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里我以“Knowing that there are tigers in the mountains, they prefer to travel in the mountains.”为例

以空格隔开分离:

 while ((retptr=strtok(ptr, " ")) != NULL) {
        printf("substr[%d]:%s\n", i++, retptr);
        ptr = NULL;
    }

运行结果:

以逗号隔开:

在关于一些字符串的处理上,这个函数很轻松的帮我们得到想要的分离结果。

#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
    char test_str[] = "Knowing that there are tigers in the mountains, they prefer to travel in the mountains.";
    char *ptr,*retptr;
    int i=0;
 
    ptr = test_str;
 
    while ((retptr=strtok(ptr, ",")) != NULL) {
        printf("substr[%d]:%s\n", i++, retptr);
        ptr = NULL;
    }
 
    return 0;
}

 

 

 

#include <stdio.h>
#include <unistd.h>
#include <malloc.h>
#define MAX_LINE_SIZE 1024
int main(void)
{
      unsigned int type;
      unsigned int data_length;
      unsigned int  address;
      char *p_data = NULL;
      p_data = (char *)malloc(MAX_LINE_SIZE * sizeof(char));
   	if (NULL == p_data) 
       {
        	printf("malloc line buffer error. \n");
		return(1);
    	}
    sscanf("S218FE8020F2FEC013EC31270BED31180A30700434F920F10A0B", "S%1x%2x%4x%x",&type, &data_length, &address,p_data);
	printf("type :S%x\n", type);
	printf("data_length:0x%x\n", data_length);
	printf("address:0x%x\n", address);
	printf("p_data :%s\n", p_data);
  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ya土豆儿~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值