我们登上并非我们所选择的舞台,演出并非我们所选择的剧本。|

乐池

园龄:3年4个月粉丝:0关注:7

1.4字符串char

头文件#include <cstring>

1.ASCII码对照表

int 48表示0,65表示A,97表示a

输入一行字符,统计数字和字母各出现了多少次

 

2.字符串读入

字符使用单引号引起来的,字符串是用双引号。

字符串就是字符数组加上\0

可以使用字符串来初始化字符数组,但是因为要加\0,所以字符数组的长度至少要比字符串多1。

定义字符串从第二个开始输出,如char a[] = {'A', 'B', 'C', 'D', '\0'},用a+1;a = "ABCD"也是同理。代码如下:

 

 用双引号引起来直接定义字符串,但是是char a3[4] = "C++";只定义3个长度的话会报错,要多一个长度自动添加空字符。

 

用scanf读入的时候不用加&符号,但是读入某一元素需要,如scanf("%s",&a[1])。代码如下:

int main(){
    char a[100];
    scanf("%s",a);
    //scanf("%s",a+1); 从1开始定义; 或cin>>a+1;
    printf("%s ",a);
    system("pause");
}

字符串用scanf和cin读入是碰到空格、回车就停止读入,所以读入多个用空格啥的隔开的字符串用fgets(字符串,最多读入多少次,stdin)。代码如下

复制代码
#include <bits/stdc++.h>
using namespace std;
int main(){
    char a[100];
    string s;
    fgets(a,100,stdin);
    getline(cin,s);
    cout<<a<<endl;
    cout<<s<<endl;
}
复制代码

运行结果如下:

 

string后面不能加【】。。。

或者可以写cin.getline(a,100)读入char

int main(){
    char a[100];
    cin.getline(a,100);//数字是最多读入多少次
}

3.字符串输出puts(),需要使用<cstdio>头文件

int main(){
    char a[100];
    fgets(a,100,stdin);
    puts(a);//输出a
    system("pause");
}

4.相关函数

字符串长度strlen

cout<<strlen(a)<<endl;

也可以用循环实现,代码如下:

int len = 0;
for(int i = 0;a[i];i++) len++;
cout<<len<<endl;

 

比较两个字符串strcmp(),进行字典序比较

int main(){
    char a[]= "abc";
    char b[]= "abd";
    cout<<strcmp(a,b)<<endl;//小于输出-1
    cout<<strcmp(b,a)<<endl;//大于输出1
    cout<<strcmp(a,"abc")<<endl;//等于输出0,可以直接在里面写字符串
    system("pause");
}

 

复制另一个字符串strcpy()。

strcpy(b,a);//把a复制给b

 以上三个方法都会把字符串循环一次,所以

for(int i = 0 ; i < strlen(a); i++) cout<<a[i]<<endl;

这是两重循环

本文作者:乐池

本文链接:https://www.cnblogs.com/ratillase/p/15497647.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   乐池  阅读(245)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起