【问题标题】:Simple if character does not equal [duplicate]如果字符不等于简单[重复]
【发布时间】:2018-03-16 13:48:12
【问题描述】:
void encode(char* dst, const char* src) {
    while (1) {
       char ch = *src;
       if (!ch || ch != '0','1','2','3') { //pseudo-code
          *dst = 0;
          return;
       }

size_t count = 1;
       while (*(++src) == ch)
          ++count;

       *(dst++) = ch;
       dst += sprintf(dst, "%zu", count);
}

我怎么说,ch 不等于数字.. 然后返回。我也在尝试摆脱无限循环。

【问题讨论】:

  • 你知道isdigit()函数吗?
  • 另外,使用 sscanf("%[0-9]") 有什么问题

标签: c character-encoding


【解决方案1】:

试试这个:

#include <ctype.h>

void encode(char* dst, const char* src) {
    while (1) {
       char ch = *src;
       if (!isdigit(ch)) { //Should works
          *dst = 0;
          return;
   }
   // Rest of the method
}

isdigit(int) 返回true 如果字符是整数(如'1'、'2'、...、'9')或false 在其他情况下。

(我想无限循环是故意做的)

【讨论】:

  • 完美 - 谢谢!
  • '42' 无效
  • 是的,你是对的,对不起:)
  • !ch 是多余的,isdigit 知道这一点
  • @sgerbhctim 你能验证答案吗?
【解决方案2】:

isdigit 有效,但为了完整起见,您将开始编写自己的 char 范围检查:

void encode(char* dst, const char* src) {
    while (1) {
        char ch = *src;
        // the char numeric value minus the 
        // numeric value of the character '0'
        // should be greater than or equal to
        // zero if the char is a digit,
        // and it should also be less than or
        // equal to 9
        if (!ch || (ch - '0' >= 0 && ch - '0' <= 9)) { 
            *dst = 0;
            return;
        }
        // ...
    }
}

正如 Nicolas 所说,你需要保证你会退出循环。

【讨论】:

    【解决方案3】:

    这是我为您编写的一个小代码,它将解析所有src 字符串,并判断该字符串是否为数字。您的while(1) 可能遇到的问题是无限循环,您只是在寻找第一个字符,所以如果我将2toto 作为参数传递,它会说好的,这是一个数字。

    如果 src 是数字,则此函数返回 true,否则返回 false。

    #include <stdbool.h>
    
    bool encode(char* dst, const char* src) {
      int i = 0;
      char ch;
    
      while (src[i] != '\0')
        {
          ch = src[i];
          if (!isdigit(ch)) { //pseudo-code                                                                                                                                                                                
            *dst = 0;
            return false;
          }
          i++;
        }
      return true;
    }
    

    【讨论】:

    • Oh le beau code :o
    • @YaatSuka bah tu sais la piscine ca forge un homme hein.. xD
    • 究竟是什么'\0'
    • 这个以 null 结尾的字符 @sgerbhctim 它标志着字符串的结尾。
    • 另外,我如何将它与我的上述编辑整合起来
    猜你喜欢
    • 2022-09-26
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    相关资源
    最近更新 更多