Today, making the code handling time (^ - ^), suddenly found such a problem. I have a string of this type is probably: you okay ^ 201.202.201.201 ^. I just need to own it in front of the Chinese, but the server was mentally challenged me add a ^ 201.202.201.201 ^, but each one has this, I will of course removed. But when they found during the operation there is no good way to accomplish this task. I want the best result is one step, but the character segmentation function basically from front to back, I can not guarantee the string does not appear in front of the "^" this character. In order to achieve this then my purpose I can do anything, so it was ugly the following code:
char pcDesc[30] = "你好呀^201.202.201.201^"; //模仿服务器的数据
int Count = 0;
for(int i = strlen(pcDesc); i >= 0; i--)
{
if('^' == pcDesc[i])
{
Count++;
if(2 == Count)
{
pcDesc[i] = '\0';
break;
}
}
}
This code I can not tolerate too strong, so I found strrchr this function. Function is explained as follows:
The strrchr () function is used to find the position of a character in a string the last occurrence of that prototype:
char * The strrchr (const char * str, int C);
Parameters to find a string str, c is to be character look.
strrchr () will find the string str in the last occurrence of the character c address, the address and return.
Note: NUL marks the end of the string str will be included in the search range, so after a group of str characters can also be positioned.
[Return value] if found return to the position of the last occurrence of the character, otherwise returns NULL.
So then into a code like this:
char pcDesc[30] = "你好呀^201.202.201.201^"; //依旧模仿服务器数据
pcDesc[strlen(pcDesc)-1] = '\0';
char *tep = strrchr(pcDesc, '^');
if(null != tep)
{*tep = '\0';}
printf("%s\n;", pcDesc);
This felt much better, although still very low, but much stronger than the original.
Summary: limited, it can only wrote this same again. Although I think STL sure there are many more convenient approach, but the current level is not, this is it. After thought a good way would be to revise again. Daniel also welcome to guide the way to a more powerful cool.