2013-09-27 108 views
0

我需要一个像memchr()函数,但它应该能够找到一个子串(字符串),不是唯一的单个字符。 它应该返回在字符串中找到的第一个匹配项。如何找到字符串中第一次出现的字符串

例如

p1 = afunclikememchr(str1,"here the function that can locate this substring",200); 

要MODS的:我加入了C++的标签,因为这也关系到C++

一言以蔽之:我想那被称为memstr()功能,常规。

此外,我必须使用C标准库,而不是C++,并且该函数在创建'\0'字节时不应停止。

+2

会工作的strstr你? http://linux.die.net/man/3/strstr – dbeer

+3

[strstr]有什么问题(http://en.cppreference.com/w/c/string/byte/strstr)? – P0W

+0

标准::搜索做你想要的。 – john

回答

0

你考虑过strstr()吗?

http://pubs.opengroup.org/onlinepubs/009695399/functions/strstr.html

的的strstr()函数将字符串 在找到第一个匹配的字节序列的s1指向的(不包括终止 空字节)在字符串中由S2指向。

+0

是的,但它停止,只要它发现'\ 0' – user2400925

+0

如果有'\ 0' _in it_它是**不是字符串**,根据定义。一个字符串终止于第一个'\ 0'的前面(也就是说)或许你应该改写一下你的问题?(在示例字符串中没有'\ 0') – wildplasser

1

既然你标记这个问题既cc++(这是错误的),我利用这个事实来回答它,如果它是一个C的问题(我不知道这是否真的是) :

所以你正在寻找像memstr()这是不是一个标准功能,但我有一个执行here

或者只是使用GNU扩展memmem(),如果有的话,你不介意是不标准的。

+0

感谢您的回答我添加了这个,因为您可以在C++项目中使用C库。 – user2400925

+0

但是有没有其他方法与ANSI C? – user2400925

+0

@ user2400925 No. – 2013-09-27 18:16:44

0

您需要相当于strstr才能在通用数组上工作。这是我从你的问题中得出的结论。没有memstr,因为你可能已经找到了,所以你将不得不写你自己的。

事情是这样的:

size_t memstr(const unsigned char* arr, size_t length, const unsigned char* tofind, size_t flength) { 
    for(size_t i = 0; i < length-flength; ++i) { 
     if(memcmp(arr+i, tofind, flength) == 0) 
     return i; 
    } 

    return -1; //highest possible unsigned value - eg std::string::npos often implemented like this. 
} 


int main() { 
    const unsigned char arr1[] = {1,2,3,4,5,6,7,8,9,0,3,3,3,3,4,4,4,4,4}; 
    size_t sz = sizeof(arr1)/sizeof(arr1[0]); 
    const unsigned char fnd[] = {3,3,3}; 

    size_t where = memstr(arr1, sz, fnd, 3); 
    return 0; 
} 
相关问题