在我的程序中,我不知道如何检查第一个空格的数组
例如
char *array[] ={'a','d','d','M',' ','-','P',' ','e'};
如何获取第一个空格并在数组
之前得到第一个空格这是我的计划:
printf("Please enter appointment: \n");
n = read(STDIN_FILENO,buf,80); /* read a line */
int result=strncmp(buf, "addM", get first space before length);
switch (result)
case 0: go to other function
或其他比较数组字符串
之前的第一个空格的方法答案 0 :(得分:2)
您可以使用strchr()
在字符数组中查找字符:
#include <string.h>
char *space_ptr = strchr(array, ' ');
int posn = -1;
if (space_ptr != NULL)
{
posn = space_ptr - array;
}
答案 1 :(得分:1)
/* buffer large enough to hold 80 characters */
char buf[80];
int i;
int n;
printf("Please enter appointment: \n");
n = read(STDIN_FILENO,buf,80); /* read a line */
/* a keyword to search */
#define KEYWORD_ADDM "addM"
#define KEYWORD_ADDM_SZ (sizeof(KEYWORD_ADDM)-1)
/* loop-find first space */
for ( i = 0; i < n; i++ )
{
if ( buf[i] == ' ' )
break;
}
if ( i == n )
{
/* space was not found in input */
}
else
{
/* space was found in input at index i */
if ( ( i >= KEYWORD_ADDM_SZ ) &&
( strncmp( &buf[0], KEYWORD_ADDM, KEYWORD_ADDM_SZ ) == 0 ) )
{
/* match */
}
else
{
/* not a match */
}
}
答案 2 :(得分:0)
我建议您使用内置库string.h它包含许多可以帮助您解析字符串的函数。
请参阅:
string.h - strtok,strchr,strspn。