C ++如何比较字符串和指针忽略空格?

时间:2013-11-16 09:42:16

标签: c++

我必须比较2个字符串...忽略其中的空格,例如:

int cmp("a b c ", "abc") == 0;

如果两者相同,则返回0;

else if s1 is bigger than s2, return 1; else return -1; e.g:
int cmp(" aaab", "aaa") == 1;

int cmp("aaa" , "aa  ab") == -1;

如何通过将字符串作为指针和pointerarithmetics传递来实现这一点?

#include <iostream>

using namespace std;

int strcmp_ign_ws(const char * s1, const char * s2) {
    int count1(0);
    int count2(0);  

    while (*s1 != '\0' || *s2 != '\0') {            

    if (*s1 == '\0') //if s1 finished, do nothing
    {
        continue;
    }
    if (*s2 == '\0') //if s2 finished, do nothing
    {
        continue;
    }

    if ( *s1 == ' ' ) {
        s1++;           //if whitespace, go on to next char
    }

    if (*s2 == ' ') {
        s2++;           //if whitespace, go on to next char
    }

    if (*s1 == *s2) {  //if same chars, increase counters;go to next char
        s1++;
        s2++;
        count1++;
        count2++;
    }
    if (*s1 > *s2) {
        count1++;
        s1++;
        s2++;
    }
    if (*s1 < *s2) {
        count2++;
        s1++;
        s2++;
    }
    /**
        while (*s1 == *s2) {
            if (*s1 == 0) 
            {
                return 0;
            }
            s1++;
            count1++;
            s2++;
            count2++;
        }**/


}
    return (count1 - count2);

}

int main(){

char a[] = "Hallo Welt!!!";
char b[] = "Hallo Welt";

int result(0);

result = strcmp_ign_ws(a,b);

cout << result << endl;

return 0;

}

编辑:我可能只使用strlen,没有其他内置函数......或字符串

2 个答案:

答案 0 :(得分:3)

在第一步,将continue替换为break。否则它会进入无限循环。你在循环中增加了那些指针,但是一旦用\0检查它们。要跳过空格,您还需要使用内部循环。

根据this strcmp实施情况,我做了一些更改然后:

int strcmp_ign_ws(const char *s1, const char *s2)
{
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;

    while (*p1)
    {
        while (isspace(*p1)) p1++;
        if (!*p1) break;

        while (isspace(*p2)) p2++;
        //if (!*p2) break;

        if (!*p2) return  1;
        if (*p2 > *p1) return -1;
        if (*p1 > *p2) return  1;

        p1++;
        p2++;
    }

    if (*p2) return -1;

    return 0;
}

答案 1 :(得分:1)

此算法的通常想法是:

int strcmp_ign_ws(const char *s1, const char *s2) {
  const char *p1 = s1, *p2 = s2;

  while (true) {
    while (*p1 != '\0' && isspace((unsigned char)*p1)) p1++;
    while (*p2 != '\0' && isspace((unsigned char)*p2)) p2++;
    if (*p1 == '\0' || *p2 == '\0') {
      return (*p2 == '\0') - (*p1 == '\0');
    }
    if (*p1 != *p2) {
      return (unsigned char)*p2 - (unsigned char)*p1;
    }
    p1++;
    p2++;
  }
}