C语言的字符串操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qiantanlong/article/details/78498665

在 C 语言中,字符串的使用需要注意,字符串实际上是使用字符 '\0' 终止的一维字符数组。下面的声明和初始化创建了一个 "Hello" 字符串。由于在数组的末尾存储了空字符,所以字符数组的大小比单词 "Hello" 的字符数多一个。

//如果按照字符数组的定义, "Hello" 五个字符,需要包含一个'\0'终止符,也就是要初始化char[6],而不能是char[5]。这个需要特别注意。

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


依据数组初始化规则,您可以把上面的语句写成以下语句:

char greeting[] = "Hello";


1、字符串的复制

#include<stdio.h>
#include<string.h>

void main() {
	char name[] = "Tom";
	char sdress[] = "Hello";
	printf("name=%s\n", name);
	printf("sdress=%s\n", sdress);
	strcpy_s(name,sizeof(sdress)/sizeof(char), sdress);
//第二个参数是缓冲区,要复制的字符串的字节大小总和
printf("sdress=%s\n", sdress);printf("name=%s\n", name);getchar();}
2、字符串A追加到字符串B后面
#include<stdio.h>
#include<string.h>

void main() {
	char name[] = "Tom";
	char sdress[] = "Hello";
	strcat_s(name, (sizeof(sdress)+sizeof(name))/sizeof(char), sdress);//第二个参数是缓冲区,要拼接的字符串的字节大小总和
	printf("sdress=%s\n", sdress);
	printf("name=%s\n", name);
	getchar();
}

3、获取字符串长度
#include<stdio.h>
#include<string.h>

void main() {
	char name[] = "Tom";
	char sdress[] = "Hello";
	int len=strlen(sdress);
	printf("%d\n", len);
	printf("sdress=%s\n", sdress);
	printf("name=%s\n", name);
	getchar();
}

4、判断字符串1与字符串2是否相同-字符串的比较是比较字符串中各对字符的ASCII码
#include<stdio.h>
#include<string.h>

void main() {
	char name[] = "Hel";
	char sdress[] = "Hel";
	int result=strcmp(name, sdress);
	printf("%d\n", result);
	printf("sdress=%s\n", sdress);
	printf("name=%s\n", name);
	getchar();
}


a:字符串1小于字符串2,strcmp函数返回一个负值;
b:字符串1等于字符串2,strcmp函数返回零;
c:字符串1大于字符串2,strcmp函数返回一个正值;
         首先比较两个串的第一个字符,若不相等,则停止比较并得出大于或小于的结果;如果相等就接着 比较第二个字符然后第三个字符等等。如果两上字符串前面的字符一直相等,像"hello"和"helloworld"   那样,   前五个字符都一样,   然后比较第六个字符,   前一个字符串"hello"只剩下结束符'/0',后一个字符串"helloworld"剩下'world','/0'的ASCII码小于'w'的ASCII 码,所以得出了结果。因此无论两个字符串是什么样,strcmp函数最多比较到其中一个字符串遇到结束符'/0'为止,就能得出结果。
注意:字符串是数组类型而非简单类型,不能用关系运算进行大小比较。  
         if("hello">"helloworld")   /*错误的字符串比较*/
         if(strcmp("hello","helloworld")   /*正确的字符串比较*/

5、获取字符串中指定字符第一次出现的指针
#include<stdio.h>
#include<string.h>

void main() {
	char name[] = "name";
	char sdress[] = "Hel";

	char *result = strchr(name, 'm');
	printf("%#x\n", result);
	printf("%c\n", *result);
	printf("sdress=%s\n", sdress);
	printf("name=%s\n", name);
	getchar();
}

6、获取字符串中指定字符串第一次出现的指针
#include<stdio.h>
#include<string.h>

void main() {
	char name[] = "name";
	char sdress[] = "Hel";

	char *result = strstr(name, "me");
	printf("%#x\n", result);
	printf("%c\n", *result);
	result++;
	printf("%c\n", *result);
	printf("sdress=%s\n", sdress);
	printf("name=%s\n", name);
	getchar();
}




 
 
 

猜你喜欢

转载自blog.csdn.net/qiantanlong/article/details/78498665