How to left trim a string in C

1 Answer

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);
        }
    }
}
  
int main() {
    char s[50] = "    c python c++ java php   ";
    
    printf("'%s'\n", s);
    
    printf("%i\n", strlen(s));
    ltrim(s);
    printf("%i\n", strlen(s));
     
    printf("'%s'\n", s);
     
    return 0;
}
      
     
     
      
/*
run:
       
'    c python c++ java php   '
28
24
'c python c++ java php   '
  
*/
  

 



answered Jun 24, 2020 by avibootz
edited Feb 14, 2024 by avibootz

Related questions

1 answer 136 views
136 views asked Jul 9, 2020 by avibootz
2 answers 189 views
189 views asked Aug 21, 2020 by avibootz
1 answer 150 views
1 answer 143 views
143 views asked Jul 11, 2020 by avibootz
1 answer 165 views
165 views asked Jul 11, 2020 by avibootz
1 answer 130 views
130 views asked Jul 10, 2020 by avibootz
1 answer 134 views
134 views asked Jul 10, 2020 by avibootz
...