简体   繁体   中英

Convert only first word of string to lower case

I have this function

char toLowerCase(char buf[]){
  for(int i =0; buf[i]; i++){
    buf[i] = tolower(buf[i]);
  }
 return *buf;
}

which gives the result

INPUT: HELoooO OOOOO
RESULT: heloooo ooooo

How do I modify this so that it only converts the first string to lower case ie. stop after " "?

I have attempted using strtok but it returns a segmentation fault after the first string.

buf is a char array. You cannot check only for 0 (what you currently do), you also have to check for a whitespace. You can use the && operator to do this:

for(int i =0; buf[i] && buf[i] != ' '; i++){

Then the condition triggers if buf[i] is a \\0 or buf[i] is a space.

Simply exit the loop after the first space:

for (int i = 0; buf[i] && !isspace(buf[i]); ++i)
  buf[i] = tolower(buf[i]);

isspace is defined in ctype.h just as tolower .

Some people will argue that using pointers will make the loop more readable but it's technically equivalent.

for (char * s = buf; *s && !isspace(*s); ++s)
  *s = tolower(*s);

If you want to skip over leading space, you'll need to modify the condition a little.

char * s = buf;
for (; *s && isspace(*s); ++s)
  continue;  /* skip leading space */
for (; *s && !isspace(*s); ++s)
  *s = tolower(*s);

Just change the condition that keeps the for loop running:

void toLowerCase(char buf[]){
  for(int i =0; buf[i] && buf[i] != ' '; i++){
    buf[i] = tolower(buf[i]);
  }
}

I also removed the return value, since what you are returning is the first character of the string, which I don't think is what you intended ( *buf is the same as buf[0] ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM