How to remove the leading and trailing commas from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void trim_commas(char *str) {
    char *start = str;
    char *end = str + strlen(str) - 1;

    // Remove leading commas
    while (*start == ',') {
        start++;
    }

    // Remove trailing commas
    while (end > start && *end == ',') {
        *end = '\0';
        end--;
    }

    // Shift the trimmed string to the beginning
    if (start != str) {
        memmove(str, start, end - start + 2);
    }
}

int main() {
    char str[] = ",,,,C Programming,,,";
    
    trim_commas(str);
    
    printf("Trimmed string: '%s'\n", str);
    
    return 0;
}



/*
run:

Trimmed string: 'C Programming'

*/

 



answered Mar 5, 2025 by avibootz

Related questions

1 answer 196 views
3 answers 292 views
2 answers 237 views
1 answer 185 views
3 answers 281 views
2 answers 210 views
...