string.h(二)C的字符串分隔函数strtok()

char *strtok(char *str1, char *str2); 

strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串,当strtok()在参数s的字符串中发现到参数delim的分割字符时则会将该字符改为\0 字符。在第一次调用时,strtok()必需给予参数s字符串(此时返回分割符前面的字符串),往后的调用则将参数s设置成NULL(返回分隔符后的字符串)。每次调用成功则返回被分割出片段的指针,当没有被分割的串时则返回NULL。

注意:会忽略掉连续的分隔符

下面程序输出为:

[abc]

[d]

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

int main(void){
	//如果有连续的分隔符,则会被忽略掉
	char input[]="abc,,d,,";
	char *p;
	p=strtok(input, ",");
	if(p)
		printf("[%s]\n", p);

	p=strtok(NULL, ",");
	if(p)
		printf("[%s]\n", p);

	p=strtok(NULL, ",");
	if(p)
		printf("[%s]\n", p);

	while(1){}
	return 0;
}

举例:IP合法性

详细描述:

请实现如下接口

boolisIPAddressValid(constcharpszIPAddr)

输入:pszIPAddr 字符串

输出:true 有效的IP地址,false,无效的IP地址

 

约束

1. 输入IP为XXX.XXX.XXX.XXX格式

2. 字符串两端含有空格认为是合法IP

3. 字符串中间含有空格认为是不合法IP

4. 类似于 01.1.1.1, 1.02.3.4  IP子段以0开头为不合法IP

5. 子段为单个0 认为是合法IP,0.0.0.0也算合法IP

<!--EndFragment-->
#include "IPAddressValid.h"
#include <stdio.h>
#include <string.h>
#include <string>


//对每个字段进行检查
bool check_token(char *token){
	//printf("token[%s]\n", token);
	if(token==NULL || token=="")
		return false;

	//0开头又不是单个0的认为不合法
	int token_len=strlen(token);
	if(token_len>=2 && *token=='0'){
		return false;
	}

	//必须在0~255
	int i=atoi(token);
	if(i<0 || i>255)
		return false;
	
	return true;
	
}

bool isIPAddressValid(const char* pszIPAddr)
{
    // 请在此处实现
	if(pszIPAddr==NULL){
		return false;
	}

	char *pszIPAddr2=const_cast<char *>(pszIPAddr);

	
	//去掉首尾空格pIP[0 ... pIpLen)
	int len=strlen(pszIPAddr);
	int preBlankNum=0;
	int postBlankNum=0;
	
	char *p=NULL;
	p=pszIPAddr2;
	while(*p==' '){
		preBlankNum++;
		++p;
	}

	p=pszIPAddr2+len-1;
	while(p>=pszIPAddr2 && *p==' '){
		postBlankNum++;
		--p;
	}

	char *pIP=NULL;
	int pIpLen=len-preBlankNum-postBlankNum;
	pIP=(char *)malloc(sizeof(char)*(pIpLen+1));
	for(int i=0;i<pIpLen;i++){
		*(pIP+i)=*(pszIPAddr+i+preBlankNum);
	}
	*(pIP+pIpLen)='\0';
	//printf("--->[%s]\n", pIP);

	if( *pIP=='.' || *(pIP+pIpLen-1)=='.')
		return false;

	//字符串中间含有空格认为是不合法IP,并且为.或者数字
	for(int i=0;i<pIpLen;i++){
		if( !(*(pIP+i)>='0'&& *(pIP+i)<='9') && !(*(pIP+i)=='.') ){
			return false;
		}
	}

	//用.来split字符串
	char *delim=".";
	char *token=NULL;

	int token_num=0;

	token=strtok(pIP, delim);
	if(token!=NULL){
		token_num++;

		bool flag=check_token(token);
		if(flag==false)
			return false;
	}

	while(token!=NULL){
		token=strtok(NULL, delim);
		printf("[%s] ", token);

		if(token!=NULL){
			token_num++;
			bool flag=check_token(token);
			if(flag==false)
				return false;
		}
	}

	if(token_num!=4)
		return false;

    return true;
}

猜你喜欢

转载自chuanwang66.iteye.com/blog/1991946