0

I was looking for a standard way to remove leading spaces, and I found a pretty simple way using pointers and isspace(), however our professor won't allow us to use the <ctype.h> library. Would the following work?

char LeadingSpace(char *line) {
    while (line[0] == ' ') {
        line++;
    }
    return line;
}

I'm new to C so not entirely sure how pointers work, but if I move the pointer everytime I find a leading space, then I would only have to check line[0], right?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Quinn Tai
  • 55
  • 1
  • 7
  • 3
    Yes this code would do what you want, however, if `line` was allocated using `malloc()` you cannot use the returned pointer for `free()`. Also, it seems that you missed a `*` in the function definition. And finally, you should be aware that `isspace()` not only ignores `' '` but `'\t'`, `'\n'` and `'\r'` too. – Iharob Al Asimi Dec 12 '15 at 18:51
  • @iharob Alright, thanks so much! Learned a lot just from that. – Quinn Tai Dec 12 '15 at 18:55

2 Answers2

1

Yes - Checking line[0] == ' ' is fine:

But this line

char LeadingSpace(char *line) {

should be

char* LeadingSpace(char *line) {

As you are returning a character pointer

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

try this

char* LeadingSpace(char *line) {
    while (line[0] == ' ' || line[0] == '\t' || line[0] == '\n' || line[0] == '\r') {
        line++;
    }
    return line;
}

or this using string.h header

char* LeadingSpace(char *line) {
    while (strchr(" \t\r\n", line[0])) {
        line++;
    }
    return line;
}
Luis Daniel
  • 687
  • 7
  • 18