How to trim a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
    
void ltrim(char *s) {
    char spaces[] = "\n\t\v\f ";
        
    size_t total_spaces_to_trim = strspn(s, spaces);
    if (total_spaces_to_trim > 0) {
        size_t len = strlen(s);
        if (total_spaces_to_trim == len) {
            s[0] = '\0';
        }
        else {
            memmove(s, s + total_spaces_to_trim, len + 1 - total_spaces_to_trim);
        }
    }
}
  
void rtrim(char *s) {
    char spaces[] = "\n\t\v\f ";
    int len = strlen(s) - 1;
    while (len >= 0 && strchr(spaces, s[len]) != NULL) {
        s[len] = '\0';
        len--;
    }
}
  
void trim(char *s) {
    rtrim(s);
    ltrim(s);
}
   
int main() {
    char s[64] = "    c python c++ java php   ";
     
    printf("'%s'\n", s);
    printf("%zu\n", strlen(s));

    trim(s);

    printf("%zu\n", strlen(s));
    printf("'%s'\n", s);
      
    return 0;
}
       
      
      
       
/*
run:
        
'    c python c++ java php   '
28
21
'c python c++ java php'
   
*/

 



answered Jun 25, 2020 by avibootz
edited Dec 5, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>

void trim(char *str) {
    char *start = str;
    
    while (*start == ' ') start++;
    
    char *end = str + strlen(str) - 1;

    while (end > start && *end == ' ') end--;
    *(end + 1) = '\0'; 

    // void *memmove(void *destination, const void *data_to_be_copied, size_t total_bytes)
    memmove(str, start, end - start);
}

int main() {
    char str[] = "   c programming    ";
    
    printf("'%s'\n", str);
    
    trim(str);
    
    printf("'%s'\n", str);

    return 0;
}



/*
run:

'   c programming    '
'c programminming'

*/

 



answered Feb 14, 2024 by avibootz

Related questions

1 answer 94 views
94 views asked Jun 25, 2020 by avibootz
1 answer 137 views
137 views asked Jun 24, 2020 by avibootz
1 answer 203 views
3 answers 420 views
1 answer 74 views
74 views asked Nov 23, 2024 by avibootz
1 answer 139 views
139 views asked Jul 9, 2020 by avibootz
1 answer 136 views
136 views asked Jul 9, 2020 by avibootz
...