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) / sizeof(int));
	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: /

发布了108 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_33242956/article/details/104925746
今日推荐