gpt4 book ai didi

c - 在 C 中,有一种方法可以知道何时到达字符串末尾。有没有办法在向后迭代时知道开始?

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:47 24 4
gpt4 key购买 nike

我正在做 K&R 练习 5-4 (p107)。

Write the function strend(s,t) , which returns 1 if the string t occurs at the end of the string s, and zero otherwise.

我认为最好的方法是...

  • 将两个指针递增到末尾
  • 当每个字符都匹配时,通过两个字符串向后计数
  • 如果我们已经数到第二个字符串的开头,则返回 1

所以 here is what I have ...

int strend(const char *str1, const char *str2) {
int i = 0;
while (*str1++ != '\0');

while (*str2++ != '\0') {
i++;
}
i++;

while (*str2-- == *str1-- && i > 0) {
i--;
}

return (i == 0);
}

如您所见,我使用了一个计数器来判断我何时到达第二个字符串的开头。

是否有任何其他循环我可以在没有计数器的情况下使用来判断我们何时到达字符串的开头(类似于查找字符串结尾的 \0)?

谢谢。

更新

没想过使用指针 - 我仍在学习并忘记了一些事情!

我想出了这个...

int strend(const char *str1, const char *str2) {
char *start = str2;
while (*str1++ != '\0');

while (*str2++ != '\0');

while (*str2-- == *str1--) {
if (str2 == start) {
return 1;
}
}

return 0;
}

最佳答案

检查匹配的指针?

关于c - 在 C 中,有一种方法可以知道何时到达字符串末尾。有没有办法在向后迭代时知道开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3948727/

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