2

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

它应该返回my_name_is_john__

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

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

4

4 回答 4

10

也许这个?

i = j = 0;
while (s[i] != '\0') {
        if (!isupper(s[i]) 
                t[j++] = s[i];
        i++;
}
t[j] = '\0';
于 2011-02-07T23:43:09.377 回答
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
于 2011-02-07T23:39:17.317 回答
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);
}
于 2011-02-08T00:02:32.320 回答
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;
}
于 2011-02-08T00:38:07.000 回答