How to remove all non-ASCII characters from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <ctype.h> // isprint

void remove_non_ascii(char *str) {
    char *src = str, *dst = str;

    while (*src) {
        if (isprint((unsigned char)*src) && (unsigned char)*src <= 127) {
            *dst++ = *src;
        }
        src++;
    }

    *dst = '\0'; // Null-terminate the filtered string
}

int main() {
    char input[] = "©€ABC£µ¥xyz!® 123 こんにちは";

    remove_non_ascii(input);

    printf("Filtered string: %s\n", input);

    return 0;
}


/*
run:

Filtered string: ABCxyz! 123 

*/

 



answered Jun 12, 2025 by avibootz
edited Jun 12, 2025 by avibootz
...