【问题标题】:C loop is not iterating through string properlyC循环没有正确地遍历字符串
【发布时间】:2017-05-12 05:47:47
【问题描述】:

我正在使用下面的方法来遍历一个字符串:

char is_words(char *word)
{
  if (word != NULL) {
    for (int i = 0; i<strlen(word)-1; i++) {
      char c = word[i];
      printf("c is: %c\n", c);
      if (!isalpha(c) || !isspace(c)) {
        return c;
      }
    }
  }
  return 'a';
}

然而使用它时,它只打印出“c is X”,其中 X 是字符串的第一个字母。为什么不遍历整个字符串?

【问题讨论】:

  • 请提供minimal reproducible example。例如我们怎么知道字符串不是像“123”这样会导致第一个return执行的?
  • 可能需要将if语句中的||替换为&amp;&amp;
  • return 终止函数执行并将控制权返回给调用者函数。
  • 请注意,您在 each 迭代中计算 strlen(word)。还有更好的方法
  • @BasileStarynkevitch 已修复,谢谢!

标签: c string loops iteration


【解决方案1】:

它在这一行返回 C

 if (!isalpha(c) || !isspace(c)) {
        return c;
 }

函数返回值后完成执行


学习如何使用 && 和 ||

一些解释

如果 c 是 abc 符号 - isalpha(c) = true , isspace(c) = false

true || false = true

如果c 是空格符号

isalpha(c) = false , isspace(c) = true

false || true = true

如果c 是数字,你会得到错误并打印另外 1 个符号

【讨论】:

    【解决方案2】:

    1.替换这段代码:

    if (!isalpha(c) || !isspace(c)) {
        return c;
    }
    

    与:

    if (!isalpha(c) && !isspace(c)) {
        return c;
    }
    

    满足以下条件时,你想返回:

    • c 不是字母字符
    • c 不是空格

    您的条件现在返回一个字符(并因此结束函数)任一 如果它不是字母 如果不是空格。因此,通过给出一串字母,函数会将它们视为非空格,因此将在第一个字符处返回。

    2.同时替换循环条件:

    for (int i = 0; i<strlen(word)-1; i++) 
    

    与:

    for (int i = 0; i < strlen(word); i++) 
    

    因为通过检查直到strlen(word)-1 的字符,您将不会检查最后一个字符。

    【讨论】:

      【解决方案3】:

      好的,你想做什么, 1. 如果你只想打印字母, 用“继续”替换return

      【讨论】:

      • 如果遇到不是字母或空格的字符,OP 想要返回。如果他将return 替换为continue,则不会发生这种情况。
      猜你喜欢
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2014-09-19
      • 2023-03-23
      • 2016-01-24
      • 2019-08-10
      相关资源
      最近更新 更多