---
title: "c语言的split"
author: "fuliang"
date: "2009-05-21T22:58:03Z"
tags: ["C", "C#", "C++", "D语言", "J#"]
slug: "c-split"
draft: false
lastmod: "2009-07-18T18:36:39Z"
id: 393139
url: "https://fuliang.iteye.com/blog/393139"
---

leven同学提到一个简单的功能"12 22 33 22 11"中的数字放到一个数组中，但不知道数字的个数。使用指针一个一个判断是否是数字还是空白，不太爽。而java中的split可以
很爽的处理之。c语言中sscanf似乎是不错的选择，于是使用下面方法，试验成功。

```cpp

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
#define MAX_LEN 10

int main(){
	char line[] = "12 22 33 22 11";
       //the max length of int we used no more than MAX_LEN 
	char *s = (char *)malloc(MAX_LEN * sizeof(char));
	int a[max];
	char *p = line;
	int cur_len;
	int i =  0;

	while(p && sscanf(p,"%s",s) == 1){
		cur_len = strlen(s);
		s[cur_len] = '\0';
		a[i] = atoi(s);
		p += cur_len;
		p++;
		i++;
	}
	
	int j = 0;
	for(j = 0; j < i-1; j++){// the i is '\0' in s
		printf("%d\t",a[j]);
	}
	printf("\n");
}

```

sscanf用法参见<http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/>