簡體   English   中英

C程序如何檢查數組首空間

[英]C program how to Check array first space

在我的程序中,我不知道如何檢查第一個空格的數組

例如

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

或其他方法比較數組字符串前的第一個空格

您可以使用strchr()在字符數組中定位一個字符:

#include <string.h>

char *space_ptr = strchr(array, ' ');
int posn = -1;
if (space_ptr != NULL)
{
   posn = space_ptr - array;
}
  /* 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 */
    }
  }

我建議您使用內置庫string.h。它包括許多可以幫助您解析字符串的函數。

看到:

string.h-strtok,strchr,strspn。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM