[英]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. 我有一个函数,可以接受一些值作为
char array[]
参数。
These values are separated with semicolons ( ';'
). 这些值用分号(
';'
)分隔。
For example: "hello;dear;John"
例如:
"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. 因此,我试图找出一种方法,使用
strtok
删除最后一个分号之后的最后一个字符串,即"John"
。
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. strrchr
将查找strrchr
的最后一次出现。
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;
}
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.