如何检查字符串是否由C中的数字或字母组成 [英] How to check if string consist of numeric or alphabet in C

查看:308
本文介绍了如何检查字符串是否由C中的数字或字母组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些识别字符串的帮助。我有这样的传入字符串

 * H1999999#

它可能与

 * H1000000#〜* H1999999#

不同有时它是

 * H1FINE#或* H1MED#

或介于两者之间的任何其他文本。现在我已经完成了解析数字字符串并复制了整数值到一个缓冲区。这是代码。

 char H1subbuff [10]; 
char head1 [4];
char Initial [2];

char * ptr;

memcpy(Initial,& rec [0],1);
Initial [1] ='\0';

memcpy(head1,& rec [0],3);
head1 [3] ='\0';



if((strcmp(head1,* H1)== 0)&&(rec [9] =='#'))
{
memcpy(H1subbuff,& rec [3],6);
H1subbuff [6] ='\0';

H1Val = strtol(H1subbuff,& ptr,10);

//显示H1VAL
}





现在我的查询是怎么回事检查字符串是否由数字或字母组成。我需要检查* H1和#之间的部分是数字还是字母,如果它是数字,我可以使用

 strtol()

将int值复制到缓冲区中。如何将字母或文本复制到缓冲区?



注意: - 上面两个字符串的字符串长度不一样。



我尝试了什么:



我试图将数值复制到缓冲区。

解决方案

使用指针跳过前缀字母字符,然后使用 strtol [ ^ ]将数字转换为长值。然后 endptr 变量将指向第一个非数字字符,允许您进一步解析。类似于:

  char  * strData =   * H1999999#; 
char * strNum = strData + 2 ;
char * strEnd = NULL;
long lValue = strtol(strNum,& strEnd, 10 );
// strEnd现在指向#字符。


I need some help in Identifying the string. I have incoming string like this

*H1999999#

it can vary from

*H1000000#~*H1999999#

sometimes it is

*H1FINE# or *H1MED#

or any other text in between.Now what I have already done is I have parsed the numeric string and copied the integer value to a buffer. Here is the code for that.

 char H1subbuff[10];
 char head1[4];
 char Initial[2];

 char *ptr;

 memcpy(Initial, &rec[0], 1 );
 Initial[1] = '\0';

 memcpy(head1, &rec[0], 3 );
 head1[3] = '\0';



 if ((strcmp(head1,"*H1") == 0) && (rec[9] == '#'))
  {
     memcpy(H1subbuff, &rec[3], 6 );
     H1subbuff[6] = '\0';

     H1Val = strtol(H1subbuff, &ptr, 10);

     //Display H1VAL
}



Now my query is how can check if the String consist of Number or Alphabet.All I need to check if the Portion between *H1 and # is numeric or Alphabet, if it is a numeric I can use

strtol()

to copy the int value into an buffer. How can I copy the alphabet or text into an buffer?

Note :- The above two string doesn't have same string length.

What I have tried:

I have tried to copy numeric values to a buffer.

解决方案

Use a pointer to skip the prefix alphabetic characters, then use strtol[^] to convert the number to a long value. The endptr variable will then point to the first non-numeric character, allowing you to parse further. Something like:

char* strData = "*H1999999#";
char* strNum = strData + 2;
char* strEnd = NULL;
long lValue = strtol(strNum, &strEnd, 10);
// strEnd will now point to the # character.


这篇关于如何检查字符串是否由C中的数字或字母组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆