c语言---字符串

c语言的字符串:char word[ ]={'H','e','l','l','o','\0'}.


字符串是什么:以0结尾的一串字符。

1.整数的0和单引号里反斜杠0是一样的,但与单引号0不一样。

2.0标志字符结束,但不是字符串的一部分。所以字符串长度不包括这个0

3.字符串以数组形式存在,可以用指针或数组的访问。


字符串变量:

1.char *str=''hello'';

2.char word[ ]=''hello'';


字符串常量:''hello''

1.''hello''会被编译器编译成一个字符数组放在某处,这个数组长度为6,结尾的0要算进去。

2.两个相邻的字符串常量会被自动连接起来。


字符串的修改:

	char *s="hello";
	//s[0]='B';    不能对s所指的字符串改写。//s是const char*s 

应该用数组的形式表达字符串,才能修改。

char s[]="hello";
s[0]='B';

用数组还是用指针表示字符串?


字符串的输入与输出 :%s

scanf:输入hello world 或 hello回车world,scanf只会读入hello,因为scanf读到空格,回车就停了。

int a[8];

%7s:表示最多接受7个字符(为什么要定义7个,因为结尾还有个0占了一个单元。)


字符串函数:(如果要用,则必须在#include<string.h>里)

(1)strlen==>字符长度

#include<stdio.h>

int main()
{
	char a[]="hello";
	printf("strlen=%d",mylen(a));
	return 0;
} 
int mylen(const char*s)
{
	int i=0;
	int cnt=0;
	while(s[i]!=0){
		/*i++*/i++;
		//cnt++;
	}
	return /*cnt*/i;
}

(2)strcmp==>比较两个字符串,结果只有-1,0,1

#include<stdio.h>

int main()
{
	char s1[]="Abc";
	char s2[]="abc";
	printf("strcmp=%d",mycmp(s1,s2));
	return 0;
} 
int mycmp(const char*s1,const char*s2)
{
	while(*s1==*s2&&*s1!=0){  //指针法 
		s1++;
		s2++;
	}
	return *s1-*s2;
	/*int idx=0;              //数组法 
	while(s1[idx]==s2[idx]&&s1[idx]!=0){
		idx++;
	}
	return s1[idx]-s2[idx];*/
	
}

(3)strcpy==>拷贝字符串

 

 (s4)trchr==>搜索字符串

注意:strchr(s,‘l’),这里的 ‘l’ 表示字符串里的一个字符,而如果要自己输入查找某一个字符的话,则

	char ch;
	scanf("%c",&ch);
	char*p;
	p=strchr(a,ch);

 

#include<stdio.h>
#include<string.h>
int main()
{
	char s[]="hello";
	char *p=strchr(s,'l');
	printf("%s",p);
	return 0;
 } 

(5)puts函数&gets函数==>字符串的输入输出

	char a[81];
	gets(a);        //接受输入的字符串

puts(a):输出字符串a.

注意:gets函数接受含空格的字符串,而上面介绍的字符串的输入输出中的scanf,是不接受空格后的任何东西。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值