我正在使用以下代码在字符串中首次出现一个字符.但是当角色太长或者我正在搜索的角色在很远的程度上需要一些时间,这会延迟其他操作.我怎么能解决这个问题.代码如下.
注意:attrPtr是一个char *包含对包含'"'远程字符的字符串的引用.
int position = 0;
char qolon = '"';//character to search
while (*(attrPtr + position++) != qolon);
char* attrValue = NULL;
attrValue = (char*)malloc(position * sizeof(char));
strncpy(attrValue, attrPtr, position-1);
Run Code Online (Sandbox Code Playgroud)
Mat*_*hen 24
strchr通常会有点快.此外,您需要检查NUL终结器,strchr将为您处理.
char *quotPtr = strchr(attrPtr, qolon);
if(quotPtr == NULL)
{
... // Handle error
}
int position = quotPtr - attrPtr;
char* attrValue = (char*) malloc((position + 1) * sizeof(char));
memcpy(attrValue, attrPtr, position);
attrValue[position] = '\0';
Run Code Online (Sandbox Code Playgroud)
不过,我还没有测试过.
编辑:修复一个一个.
C有一个内置函数,用于搜索字符串中的字符 - strchr(). strchr()返回指向找到的字符的指针,而不是数组位置,因此你必须从返回的指针中减去指向字符串开头的指针才能得到它.您可以将您的功能重写为:
char qolon = '"';//character to search
char *found;
char *attrVal = NULL;
found = strchr(attrPtr, qolon);
if (found)
{
size_t len = found - attrPtr;
attrVal = malloc(len + 1);
memcpy(attrVal, attrPtr, len);
attrVal[len] = '\0';
}
Run Code Online (Sandbox Code Playgroud)
通过一个小的常数因子,这可能比你的原始速度快; 但是,你不会得到一个数量级的加速.在无序字符串中搜索字符基本上是字符串长度中的O(n).
| 归档时间: |
|
| 查看次数: |
80199 次 |
| 最近记录: |