gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:11:30 26 4
gpt4 key购买 nike

<分区>

我必须比较 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;

我如何通过将字符串作为指针传递并使用指针算法来实现这一点?

#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 ,没有其他内置函数......或字符串

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com