1、头文件:#include<string.h>


2、利用字符数组定义字符串:

char strTemp[] = "string tests";



3、上面的字符串在定义时进行了初始化,但是要单独给字符串赋值,不能用“=”符号。而要用字符串相关的函数。

错误示例:


strTemp = "abcd"; // 错误



正确示例:


strcpy(strTemp, "abcd"); // 注意字符串的长度



4、下面是C中的常见字符串操作:


// csdn.cpp : 定义控制台应用程序的入口点。
// 字符串操作
//

#include "stdafx.h"
#include <string.h>


int _tmain(int argc, _TCHAR* argv[])
{
	// 定义并初始化一个字符串
	char strTemp[] = "string tests";
	printf("%s\n", strTemp);

	// 错误示例
	//strTemp = "abcd";

	// 赋值
	strcpy(strTemp, "abcd");  // 确保赋值字符串的长度不大于字符数组的大小
	printf("%s\n", strTemp);

	// 部分赋值
	strncpy(strTemp, "zzzzzz", 2);
	printf("%s\n", strTemp);

	// 拼接
	strcat(strTemp, "ABCD");
	printf("%s\n", strTemp);

	// 比较
	if (strcmp(strTemp, "zzcdABCD") == 0)
	{
		printf("两个字符串相等!\n");
	}
	else
	{
		printf("两个字符串不相等!\n");  // 常用的字符串比较就是比较两个字符串是否相同
	}

	// 转化为大写
	strupr(strTemp);
	printf("%s\n", strTemp);

	// 转化为小写
	strlwr(strTemp);
	printf("%s\n", strTemp);

	// 查找字符
	char ch = 'a';
	char* result = strchr(strTemp, ch);
	if (result != 0)
	{
		printf("字符串%s中有字符%c,位置在第%d个字符。\n", strTemp, ch, result - strTemp + 1);
	}
	else
	{
		printf("字符串%s中没有字符%c\n", strTemp, ch);
	}

	// 查找字符串
	char st[] = "bcd";
	char* result_str = strstr(strTemp, st);
	if (result != 0)
	{
		printf("字符串%s中有字符串%s,位置从第%d个字符开始\n", strTemp, st, result_str - strTemp + 1);
	}
	else
	{
		printf("字符串%s中没有字符%s\n", strTemp, st);
	}

	return 0;
}



运行结果:

字符串_#include



5、上面少写了一个函数strtok,介绍一个用法的示例:分离一句话中的单词。

// csdn_strtok.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string.h>



int _tmain(int argc, _TCHAR* argv[])
{
	char string[] = "In Shaanxi Province and Xinjiang Uygur Autonomous Regionin in northwest China.\n";
	char seps[]   = " .\n";
	char *token;

	printf( "%s\n\nTokens:\n", string );
	/* Establish string and get the first token: */
	token = strtok( string, seps );
	while( token != NULL )
	{
		/* While there are tokens in "string" */
		printf( " %s\n", token );
		/* Get next token: */
		token = strtok( NULL, seps );
	}
	getchar();
	return 0;
}



运行结果:根据空格等符号 将一句话分离出单词

字符串_bc_02