C和C样式字符串中的Pascal样式字符串在一个函数中进行比较

时间:2014-12-19 22:58:24

标签: c string

我需要用C语言编写一个小函数,其中我有一个Pascal样式字符串和另一个字符串,C样式字符串。在这个函数中,我应该比较这两个字符串,如果两个字符串相同,则函数应返回true,否则返回false。

int main()
{
  char pascal_string // here I have a problem 
  char c_string[] = "Home";

  return 0;
}

2 个答案:

答案 0 :(得分:3)

简单地走下每个阵列。无需预先计算C字符串的长度

int same_pstring_cstring(const char *p, const char *c) {
  unsigned char plength = (unsigned char) *p++;  // first `char` is the length
  while (plength > 0 && *c != '\0') {
    plength--;
    if (*p != *c) {
      return 0;
    }
    p++;
    c++;
  }
  // At this point, plength is 0 and/or *c is \0
  // If both, then code reached the end of both strings
  return (plength == 0) && (*c == '\0');
}

int main(void) {
  char pascal_string[1 + 4] = "\4" "Home";
  char c_string[] = "Home";
  char c_string2[] = "Home ";
  printf("%d\n", same_pstring_cstring(pascal_string, c_string));
  printf("%d\n", same_pstring_cstring(pascal_string, c_string2));
  return 0;
}

答案 1 :(得分:2)

好的,这样的事情?

int compare(unsigned char *pascal, unsigned char *str, unsigned int strLength)
{
    unsigned int length = pascal[0];// get length of pascal string
    if(length != strLength)
        return 0; // if strings have different length no need to compare

    for(int i = 0; i<length; i++)
        if(pascal[1+i]!=str[i])
            return 0;

    return 1;
}

int main(int argc, const char * argv[])
{
    unsigned char pascal[32] = {5, 'H', 'e', 'l', 'l', 'o' };
    unsigned char *ordinaryStr = "Hello";
    int t = compare(pascal, ordinaryStr, 5);// pass length of other string manually, e.g., 5
}