C函数删除所有大写字符

时间:2011-02-07 23:31:56

标签: c string char uppercase

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

它应该返回my_name_is_john__

这不是一个很容易成为一个HW,但它在我的时区凌晨2点,我认为这将是我现在在代码中遇到的问题的解决方案!

欢迎任何帮助! 欢呼!=)

4 个答案:

答案 0 :(得分:10)

也许这个?

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

答案 1 :(得分: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

答案 2 :(得分:2)

这个怎么样?

#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);
}

答案 3 :(得分: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;
}