简体   繁体   中英

How to get a string from a string (char pointer in C)

The question is simple but the C language doesn't provide us with a useful library:

Suppose that we have this string:

char *request  = "GET /websiteos/example_of_a_simple_html_page.htm HTTP/1.1\r\n";

How can I get the following string:

/websiteos/example_of_a_simple_html_page.htm

The string I'm looking for is found between 2 spaces. The problem is that each time I will have a new request line, so I don't know the size of the string.

I thought I'd proceed like this, but it doesn't work:

char * getTheResource(char *request){
char c;
int i=4;
char *resource=(char *)malloc(20);
while   (request[i] != ' ')
{   strcat(resource, request[i]);
    i++;
}
return resource;

}

int main( int n , char *arg[] )
{   
    char *request  = "GET /websiteos/example_of_a_simple_html_page.htm HTTP/1.1\r\nHost: help.websiteos.com\r\n\r\n";
    char *res =getTheResource(request);
    printf("the ressource is :%s\n",res);
}

I'm getting a compilation error:

In function 'getTheResource':
example.c:19:3: warning: passing argument 2 of 'strcat' makes pointer from integer without a cast [enabled by default]
strcat(resource, request[i]);

So how can I solve this problem?

Consider using strchr function to find pointer to first space in your string, then pass this pointer increased by one to strchr again to get pointer to second space in your string, then copy the range from first pointer to second into output and add a null terminator.

#include <string.h>
#include <stdio.h>

void f(const char* s, char* res) {
    char* l = strchr(s, ' ');
    char* r = strchr(l + 1, ' ');
    memcpy(res, l + 1, r - l);
    res[r - l - 1] = '\0';
}

int main() {
    const char* s = "sdfasdfasdf sadf sdfasdf";
    char res[1024];
    f(s, res);
    printf("%s\n", res);
    return 0;
}
strcat(resource, request[i]);

It is wrong because request[i] is of type char and strcat require char * .

You can assign character to resource at that index using = operator instead:

int j = 0;
while(request[i] != ' ' && j < 19){  // Or the size you allocate to your pointer 
  resource[j] = request[i];
  i++;
  j++;
}
resource[j] = '\0';

EDIT-

You can also make use of strtok . Use space as delimiter and get the string you want after tokenizing (But declare request as char request[] = "your string"; in main ).

You have several problems with your code.

The strcat should not be used for copying a single character, use assignment instead.

You should always check the return from your allocations - in this case use calloc() instead of malloc() so the buffer gets initialized with NUL characters as well as allocated.

Your while loop is very dangerous as it assumes the string has at least one ' '. You should make sure to always check so you don't run off the end of your string.

If the request string is too short you will have trouble so check for the length of the input string.

You must ensure that you have enough space to hold the new string and not to overrun the new string buffer. So you need a #define to tell you how much you can fit into the new buffer.

Keep in mind that if you use the getTheResource() you must free() the memory if you are not planning on exiting the application. It is not required here because you are exiting the application but in case you use the getTheResource() somewhere else in your code you should free the returned buffer when done with it.

It is good practice to free() your memory anyway because it will help you discover errors that you didn't expect - like overrunning the resource string buffer length might not show up as an error unless you try to free the buffer and then the OS complains. Something that will get you later after you think everything is running OK (but it isn't).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NEW_STRING_MAX_SIZE 100

char *getTheResource(char *request) {
   int i=4, j=0;
   char *resource;

   // validate input string is not NULL
   if ( !request )
      return NULL;

   // allocate and initialize buffer to hold new string
   if ( !( resource = (char *)calloc(1, NEW_STRING_MAX_SIZE) ) )
      return NULL;

   // validate input string is at least 4-characters
   if ( strlen( request ) <= i )
      return resource;

   // loop through old string copying to new string char by char
   while ( request[i] != '\0' && request[i] != ' ' && j < NEW_STRING_MAX_SIZE-1 )
       resource[j++] = request[i++]; // do a character assignment rather than strcat

   return resource;
}

int main( int n , char *arg[] )
{
    char *request = "GET /websiteos/example_of_a_simple_html_page.htm HTTP/1.1\r\nHost: help.websiteos.com\r\n\r\n";
    char *res = getTheResource(request);
    printf("the ressource is :%s\n",res);

    if ( res != NULL )
       free( res );
}

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