zoukankan      html  css  js  c++  java
  • 字符串提取

    比如一个字符串“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.可用来判断字符串中两个标识符之间的字符串的长度。

  • 相关阅读:
    获取打印页号列表
    数据库设计技巧系列(三)——选择键和索引
    SQL Server2000孤立用户解决方案
    在WinForm程序中嵌入ASP.NET[转]
    再谈如何遍历Asp.net窗体下所有的控件
    数据库设计技巧系列(二)——设计表和字段
    今天下午真郁闷……
    如何实现在Asp.net下XP风格的下拉菜单
    利用SQL语句得到客户端的IP地址
    国庆节快乐……
  • 原文地址:https://www.cnblogs.com/shanlizi/p/6768544.html
Copyright © 2011-2022 走看看