【问题标题】:C function to remove all uppercase charactersC函数删除所有大写字符
【发布时间】:2011-06-23 02:41:57
【问题描述】:

我需要一个有效的 C 函数实现,该函数将被赋予一个 char[],它将从中删除所有大写字符,返回所有剩余的内容。 例如如果给出HELLOmy_MANname_HOWis_AREjohn_YOU__

它应该返回my_name_is_john__

这不是一个太容易成为硬件的硬件,但它在我的时区凌晨 2 点,我认为这将是我现在在代码中面临的问题的解决方案!

欢迎任何帮助! 干杯!=)

【问题讨论】:

  • 到目前为止您尝试过什么,为什么对您没有效果?
  • 节省内存还是节省时间?
  • 如果这“太容易”而不能成为家庭作业,那么是什么阻止你自己写呢?

标签: c string char uppercase


【解决方案1】:

就地工作:

#include <stdio.h>
#include <stdlib.h>

char* removeUpperCase(char *s) {
    char *current = s;
    char *r = s; // r is the same rewrite pointer someone else mentioned in his answer =)
    do {
        if ((*current < 'A') || (*current > 'Z')) {
            *r++ = *current;
        }
    } while (*current++ != 0);
    return s;
}

int main() {
    char *s = strdup("HELLOmy_MANname_HOWis_AREjohn_YOU__"); // needed because constants cannot be modified
    printf(removeUpperCase(s));
    free(s);
    return 0;
}

【讨论】:

    【解决方案2】:

    也许是这个?

    i = j = 0;
    while (s[i] != '\0') {
            if (!isupper(s[i]) 
                    t[j++] = s[i];
            i++;
    }
    t[j] = '\0';
    

    【讨论】:

    • 顺便说一句,如果您不想为结果使用单独的变量 t,那么只需将其替换为 s 并记住这样做:s[j] = '\0';
    • 无论如何你都需要在循环之后做t[j] = '\0';(因为你没有在NUL上输入循环体)。
    【解决方案3】:

    这个怎么样?

    #include <string.h> //strlen, strcpy
    #include <ctype.h>  //isupper
    #include <stdlib.h> //calloc, free
    
    //removes uppercase characters
    void rem_uc(char *str) {
        char *newStr = calloc(strlen(str), sizeof(char));
        char curChar;
        int i_str = 0, i_newStr = 0;
        do {
            curChar = str[i_str];
            if(!isupper(curChar)) {
                newStr[i_newStr] = curChar;
                i_newStr++;
            }
            i_str++;
        } while(curChar != 0);
        strcpy(str, newStr);
        free(newStr);
    }
    

    【讨论】:

      【解决方案4】:

      算法一些伪代码怎么样?

      initialize a rewrite pointer to the beginning of the string
      for each character in the input string that isn't nul:
          if character is not an uppercase letter:
              add the character to rewrite pointer
              increment rewrite pointer
      add nul terminator to rewrite pointer
      

      【讨论】:

        猜你喜欢
        • 2020-02-09
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        • 2013-03-12
        • 2014-07-12
        • 1970-01-01
        相关资源
        最近更新 更多