开发者

C function to remove all uppercase characters

I need an efficient implementation of a function in C that would be given a char[] and it will remove all uppercase characters from it returning everything left. e.g. if given HELLOmy_MANname_HOWis_AREjohn_YOU__

it should return my_name_is_john__

this开发者_如何学编程 is not a HW too easy to be one, but its 2am in my timezone and I think this would be a solution to a problem im facing in my code now!

any help is welcome! cheers!=)


maybe this?

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


How about an algorithm some pseudo-code?

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


How about this?

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


Works in-place:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜