如何删除C中带有strtok的char数组中的最后一个字符串?

时间:2011-11-06 02:02:47

标签: c arrays strtok

我有一个函数接受一些值作为char array[]参数。

这些值用分号(';')分隔。

例如:"hello;dear;John"

所以我试图找出一种方法,使用strtok删除最后一个分号后的最后一个字符串"John"

int remove(char lastName[]){


}

*更具体一点

我创建了这个函数,它删除了以分号分隔的值:

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;    
}

但是函数在找到分号后会删除所有内容。

2 个答案:

答案 0 :(得分:2)

strrchr会找到该字符的最后一次出现。

如果您不介意修改原始字符串,那么它应该像

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

Man Page here

答案 1 :(得分:2)

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

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

编辑:在回复您的评论时,它确实有效。我就是这样做的,我已经包含了整个程序来展示输出的例子:

#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;
}

输出:

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

您也可以直播here