[英]Set a string to a substring in C
I have a long string that I want to strip off the end.我有一根很长的绳子,我想把它的末端剥掉。 I want to get rid of everything after the character "<" (inclusively).我想摆脱字符“<”(包括)之后的所有内容。 Here is the code that works:这是有效的代码:
char *end;
end = strchr(mystring, '<');
mystring[strlen(mystring) - strlen(end)] = '\0';
So if mystring was所以如果 mystring 是
"asdfjk234klsjadflnwer023jokmnasdf</tag>alskjdflk23<tag2>akjsldfjsdf</tag2>blabla"
this code would return此代码将返回
"asdfjk234klsjadflnwer023jokmnasdf"
I'm wondering if this can be done in a easier way?我想知道这是否可以以更简单的方式完成? I know I can increment a counter over each character in mystring till I find "<" and then used that int as the index, but that seems equally troublesome.我知道我可以在 mystring 中的每个字符上增加一个计数器,直到找到“<”,然后使用该 int 作为索引,但这似乎同样麻烦。 All the other built-in string libraries don't seem useful but I'm sure I'm just looking at this in the wrong way.所有其他内置字符串库似乎都没有用,但我确定我只是以错误的方式看待这个问题。 I haven't used C for years.我已经好几年没用过 C 了。
Any help is appreciated!任何帮助表示赞赏!
Sure.当然。 This is the idiomatic way to do it:这是惯用的方法:
char *end;
end = strchr(mystring, '<');
if (end)
*end = '\0';
How about *end = '\0';
*end = '\0';
怎么样? rather than the mystring[strlen...
part?而不是mystring[strlen...
部分?
char *end;
end = strchr(mystring, '<');
if (end != NULL)
*end = '\0';
strchr() returns a pointer to the character (if found), so: strchr() 返回一个指向字符的指针(如果找到),所以:
if(end)
*end = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.