C语言从字符串中提取数字和其他字符

从字符串"100+200-50*2/5"中提取出来数字和运算符

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int analysis_data(const char *str, int *value, int *value_count, char *operator, int *operator_count)
{
	int value_index = 0;
	int operator_index = 0;
	int n = 0;

	if (str == NULL || value == NULL || value_count == NULL || operator == NULL || operator_count == NULL) {
		return -1;
	}

	while (*str != '\0') {
		n = 0;
		while (*str >= '0' && *str <= '9') {
			n = n * 10 + (*str - '0');
			str++;
		}

		if (*str == '+' || *str == '-' || *str == '*' || *str == '/') {
			operator[operator_index++] = *str;
			str++;
		}
		
		value[value_index++] = n;
	}

	*value_count = value_index;
	*operator_count = operator_index;

	return 0;
}

int main()
{
	char buffer[1024] = "100+200-50*2/5";

	int value[1024];
	int value_count = 0;
	char operator[1024];
	int operator_count = 0;
	int result = 0;
	
	memset(value, 0x00, sizeof(value));
	memset(operator, 0x00, sizeof(operator));
	
	analysis_data(buffer, value, &value_count, operator, &operator_count);

	int i = 0;
	for (i = 0; i < value_count; i++) {
		printf("value: %d\n", value[i]);
	}

	for (i = 0; i < operator_count; i++) {
		printf("operator: %c\n", operator[i]);
	}

	return 0;
}

运行结果:
value: 100
value: 200
value: 50
value: 2
value: 5
operator: +
operator: -
operator: *
operator: /

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值