查找字符串

    我们经常要用到查找某个字符串的功能,使用C++或者其他高级语言实现起来很简单;但是使用C语言实现就不那么easy了。

    首先,我们要切割字符串。

    strtok函数声明:

char *strtok_s(
   char *strToken,
   const char *strDelimit,
      char **context
);

    1. strToken

        要切割的字符串

    2. strDelimit

        分隔符

    3. context

        为空的字符串地址

    其次,需要匹配字符串

    strstr函数声明:

char *strstr(
   const char *str,
   const char *strSearch 
); // C only
    1. str

        被搜索的字符串

    2. strSearch

        要搜索的字符串


   函数getStrVal_s

char *getStrVal_s(char *str, char key[])
{
	char* strDelimit = ";";
	char *strSeq = "";
	char *context = NULL;

	char *token = strtok_s((char*)str, strDelimit, &context);
	while (token != NULL) {
		char* temp = strstr(token, key);
		if (temp != NULL)
			strSeq = temp;

		if (token != NULL) {
			token = strtok_s(NULL, strDelimit, &context);
		}
		
	}

	return strSeq;
}

   主程序:

int _tmain(int argc, _TCHAR* argv[])
{

    char string[] = "True democracy demands that citizens cannot be thrown in jail because of what they believe;and that businesses can be opened without paying a bribe;It depends on the freedom of citizens to speak their minds and assemble without fear;and on the rule of law and due process that guarantees the rights of all people";
	char* val = getStrVal_s(string, "freedom");

	printf("val: %s", val);

	return 0;
}

    本程序在VS2005编译通过。


你可能感兴趣的:(查找字符串)