检查字符串冻结的功能

时间:2014-11-10 04:44:59

标签: c arrays string strcmp strlen

该程序应该使用hydroxide函数来检查输入的字符串,看它是否以“oh”(或“ho”)结束,如果是,则返回1值。这是我写的,当我运行程序时它就冻结了。我仍然是初学者,所以如果这是一个愚蠢的问题我会提前道歉。

#include <stdio.h>
#include <string.h>

#define MAX_LEN 10

int hydroxide(char *compound);

int main(void)
{
  char compound[MAX_LEN];
  int i, num;

  printf("Enter compound> \n");
  scanf("%s", compound);

  for (i = 0; i < strlen(compound); ++i) {
    if (islower(compound[i]))
        compound[i] = toupper(compound[i]);
  }

  num = hydroxide(compound);

  printf("%d", num);

  return(0);
}

int hydroxide(char *compound)
{
  char *end[4], *temp;
  int last, status;

  last = strlen(compound);

  strcpy(end[], &compound[last - 2]);

  if (strcmp(end[last - 2],end[last - 1]) > 0) {
    temp = end[last - 2];
    end[last - 2] = end[last - 1];
    end[last - 1] = temp;
  }

  if (*end[last - 2] == 'H') {
    if (*end[last - 1] == 'O')
      status = 1;
  }

  return(status);
}

2 个答案:

答案 0 :(得分:0)

char end[4], *temp;  /* Change to end[4] */
...
...
strcpy(end, &compound[last - 2]);  /* Change to end */
...
...
/*  Commented
 * if (end[0],end[1]) > 0) {
 *  temp = end[last - 2];
 *  end[last - 2] = end[last - 1];
 *  end[last - 1] = temp;
 * }
 */
/* Condition updated */
if ( (end[0] == 'H' && end[1] == 'O') || (end[0] == 'O' && end[1] == 'H') ) {
  status = 1;
}

Live Example here

答案 1 :(得分:0)

试试这个功能。 Here the last two characters in the string are checked for 'H' or 'O'。 如果找到字符,则返回1.

int hydroxide(char *compound)
{
    int len, status = 0;

    len = strlen(compound);

    if ((compound[len - 2] == 'H' && compound[len - 1] == 'O' ) || 
            (compound[len - 1] == 'H' && compound[len - 2] == 'O')) {
            status = 1;
    }

    return status ;
}