简体   繁体   中英

How to delete the last string in an array of char with strtok in C?

I have a function which accepts some values as char array[] parameters.

These values are separated with semicolons ( ';' ).

For example: "hello;dear;John"

So I'm trying to figure out a way by using strtok to delete the last string, which is "John" after the last semicolon.

int remove(char lastName[]){


}

*To be more specific

I have created this function which removes values separated by semicolons:

int remove(char variable_Name[]){

        char *value_toRemove = getenv(variable_Name);
        char last_semicolon[] = ";";
        char *result = NULL;
        result = strtok( value_toRemove, last_semicolon );
        while( result != NULL ) {
        result = strtok( NULL, last_semicolon );
        }
        return NULL;    
}

But the function deletes everything after it finds a semicolon.

strrchr will find the last occurance of the character.

Sor if you don't mind modifyint the original string then it should be as simple as

int remove(char *lastName){
   char *pos = strrchr(lastName, ';');
   if (pos) {
      *pos = 0;
      return pos-lastName;
   }
   return 0;
}

Man Page here

char *last_semi = strrchr(lastName, ';');

if (last_semi != NULL)
   *last_semi = '\0';

EDIT: In response to your comment, it does work. This is how I'd do it and I've included the whole program to show an example of the output:

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

char *remove_end(char *str, char c)
{
   char *last_pos = strrchr(str, c);

   if (last_pos != NULL) {
      *last_pos = '\0';
      return last_pos + 1; /* pointer to the removed part of the string */
   }

   return NULL;  /* c wasn't found in the string */
}

int main(void)
{
   char s1[] = "hello;dear;John";
   char s2[] = "nothing to remove";
   char *removed;

   /* s1 */
   printf("Original string: %s\n", s1);
   removed = remove_end(s1, ';');
   printf("New string: %s\n", s1);
   printf("Removed: %s\n", removed ? removed : "NOTHING");
   /* s2 */
   printf("Original string: %s\n", s2);
   removed = remove_end(s2, ';');
   printf("New string: %s\n", s2);
   printf("Removed: %s\n", removed ? removed : "NOTHING");

   return 0;
}

Output:

Original string: hello;dear;John
New string: hello;dear
Removed: John
Original string: nothing to remove
New string: nothing to remove
Removed: NOTHING

You can also try it live here .

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