Home > OS >  Pointer at last word
Pointer at last word

Time:01-08

I'm trying to return a pointer to the last word in a string.

Example: "the sky is blue" - it should return "blue".

But I'm having problems when I have space after the string:

Example: "the sky is blue " - it returns ' '.

This is what I have come up with so far:

const char* function(const char *s)
{
   char *l;
   int length=strlen(s);

    l=(char *)(s length-1);
    while(l!=s)
    {
        if(*l==' ')
        break;

        l--;
    }
    if(l!=s)
    return l 1;
}

CodePudding user response:

  1. There are executions of your function that doesn't return a value. This is undefined behavior I believe.
  2. Your code is poorly formatted, and function is a particular confusing choice of name.
  3. You break if l pointers to a space and then return l 1 which would be the terminating '\0' in your sample data.

First let's define the delimiter, then skip over the initial ones so we start with a word. Then we find the next delimiter and skip the those if we fail to find a delimiter or we are at the end of the input then we return the last word we found. If the input doesn't contain any words the output is an empty string.

#define DELIM " "
#include <string.h>
#include <stdio.h>

const char* function(const char *s) {
    if(!s) return NULL;
    while(*s && strchr(DELIM, *s)) s  ;
    for(;;) {
        const char *last = s;
        s = strpbrk(s, DELIM);
        while(s && *s && strchr(DELIM, *s)) s  ;
        if(!s || !*s) return last;
    }
}

int main(void) {
    printf("\"%s\"\n", function("the sky is blue "));
}

example session:

"blue "

Note the trailing space. You either have to give up the const of the input or you have to make a copy if the last word so you strip trailing space(s).

CodePudding user response:

The loop while(*l!=' ') {if(isspace((unsigned char *)l)) l--; } is not working because if(isspace((unsigned char *)l)) l--; will be executed only while(*l!=' '): but if the string's last character is a space, then *l==' ', which means you are just skipping the loop. Then the correct cycle could be : while(*l==' ') {if(isspace((unsigned char *)l)) l--; }

Your original code instead returns an empty character because you point l to the latest character in the string, then when you enter the while cycle, it just exit at the first iteration because *l==' ' and then you just break the cycle. You could just move l--; before the if(*l==' ') break; instruction, but you will have the same problem when you have two or more spaces.

You could even do something simple as the following code, this will return the latest word, digit or punctuation character in the string:

const char* function(const char *s){
    char *l=(char*)(s strlen(s)-1);
    while(isspace(*l)) l--;
    while(isdigit(*l)||iscntrl(*l)||ispunct(*l)) l--;
    while(isalnum(*l)) l--;
    return l 1;
}
  • Related