首页 > 代码库 > 字符串提取

字符串提取

比如一个字符串“110,hello,119,world,120,computer”,我想提取第3个逗号“,”之后(第4个逗号","之前)的那一段,即“world”;如何用代码实现;

如下:

  ----------------------------------------------------

  #define UART_RECV_FIELD_LENTH 512
  #define UINT16 unsigned short

  -----------------------------------------------------

 

UINT16 Field( char* InputSentence,char *OutBuf,UINT16 desired_field_number)
{
	UINT16 index                = 1; 
	UINT16 index1               = 0;
	UINT16 current_field_number = 0;
	UINT16 string_length        = strlen(InputSentence);
	char return_string[UART_RECV_FIELD_LENTH] = {0};

	memset (OutBuf, 0, UART_RECV_FIELD_LENTH);

	//找到想要提取的参数位置
	while( current_field_number < desired_field_number && index < string_length )
	{
		// 判断字段分隔符及校验和定界符
		if ( InputSentence[ index ] == ‘,‘ || InputSentence[ index ] == ‘*‘ )
		{
			current_field_number++;
		}
		index++;
	}

	//提取参数字段
	if ( current_field_number == desired_field_number )
	{
			while( index < string_length      &&
				InputSentence[ index ] != ‘,‘ &&
				InputSentence[ index ] != 0x00 )
			{
				if(index1 >= UART_RECV_FIELD_LENTH)
				{
					return 0 ;
				}
				return_string[index1]= InputSentence[ index ];
				index++;
				index1++;
			}
		
	}

	memcpy(OutBuf,return_string,index1);
	return index1;
}

  

  返回值为提取字符串的长度

  char* InputSentence ,输入原始字符串指针

  char *OutBuf ,输出字符串指针

  UINT16 desired_field_number) ,提取字符串的位置

  ----------------------------------------------------------------

  如开头所假设,char *InputSentence = “110,hello,119,world,120,computer”; char OutBuf[]={0};

  调用Field(InputSentence, OutBuf, 3);  则OutBuf内容为“world”;

 

  扩展:

  1.这里的提取标识符为逗号“,”,那么如果标识符为“,”,“*”等多种,同样可以解决。

  2.如果字符串中仅为数字,对所得字符串数字化处理即可。

  3.可用来判断字符串中两个标识符之间的字符串的长度。

字符串提取