C语言字符串

在C语言中字符串是一个字符数组。

声明字符串:

#include <stdlib.h>

int main(int argc, char* argv[])
{
	char str1[] = {'h', 'e', 'l', 'l', 'o', '\0'};
	char str2[] = "hello"; //自动添加终止符'\0'
	printf("%s\n%s\n", str1, str2);	
	system("pause");
	return 0;
}

读取和输出字符串:

#include <stdlib.h>

//方法一:使用scanf、printf
int main(int argc, char* argv[])
{
	char first_name[20];
	printf("Enter your firstname:");
	scanf("%s", first_name);
	printf("%s\n", first_name);	
	system("pause");
	return 0;
}

#include <stdlib.h>

//方法二:使用gets、puts
int main(int argc, char* argv[])
{
	char first_name[20];
	puts("Enter your firstname:");
	gets(first_name);
	puts(first_name);
	system("pause");
	return 0;
}

要对字符串长度计算、字符串连接、复制等功能,则需要使用标准库中预置的函数。这些函数存放在头文件string.h中。

1.字符串长度函数strlen

size_t strlen(const char *str)

size_t 表示无符号短整数,它返回字符串的长度而不包括终止字符'\0'

#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	char str1[20] = "hello";
	printf("Length of string str1: %d\n", strlen(str1)); //5
	system("pause");
	return 0;
}

strlen和sizeof
strlen返回存储在数组中的字符串的长度,sizeof返回分配给数组的总大小

#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	char str1[20] = "hello";
	printf("strlen=%d\nsizeof=%d\n", strlen(str1), sizeof(str1)); 
    //strlen=5
    //sizeof=20
	system("pause");
	return 0;
}

2.字符串比较函数strcmp

int strcmp(const char *str1, const char *str2)

比较两个字符串并返回一个整数值。如果两个字符串相同(相等),则此函数将返回 0,不相等返回非 0。

#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	char str1[20] = "hello";
	char str2[20] = "world";
	printf("%d\n", strcmp(str1, str2));
	system("pause");
	return 0;
}

3.字符串连接函数strcat

char *strcat(char *str1, char *str2)

#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	char str1[20] = "hello";
	char str2[20] = "world";
	strcat(str1, str2);
	printf("%s\n", str1);//helloworld
	printf("%s\n", str2);//world	
	system("pause");
	return 0;
}

4.字符串复制函数strcpy

char *strcpy( char *str1, char *str2)

它将字符串str2复制到字符串str1中,包括终止字符'\0'

#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	char str1[20] = "hello";
	char str2[20] = "world";
	strcpy(str1, str2);
	printf("%s\n", str1);//world
	printf("%s\n", str2);//world
	system("pause");
	return 0;
}

5.在字符串中查找字符strchr

char *strchr(char *str, int ch)

#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
	char str1[20] = "hello";
	printf("%s\n", strchr(str1, 'o'));
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值