字符串和字符数组详解【看完立马大彻大悟】

字符数组(char ch[]):

#include<bits/stdc++.h>
using namespace std;
int main(){
    //定义s[10],最多只能存4个字符,因为s[10]='\0'
    char s[10]; //s[0],s[1],s[2]...s[9],'\0'
    scanf("%s",s); //可改为:scanf("%s",s+n); 这样做输入:s[n]~s[10]
    int len=strlen(s); //长度函数
    printf("len=%d\n",len); //长度
    for(int i=0;i<len;i++){ //输出
        printf("%c ",s[i]);
    }
    return 0;
}


字符串(string):

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s="";
    s+='a'; //加在结尾
    s+="bcde"; //加在结尾
    cout<<s<<endl;
    cout<<"len="<<s.length()<<endl; //s.length相当于s.size()
    return 0;
}


注意点:

1. 数据量比较大的时候用scanf, printf, 对应char数组
2. 数据量不大可以用cin, cout对应string类

find

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s="abcdef";
    int pos=s.find('abc'); //找到返回位置,找不到返回-1
    cout<<pos<<endl;
    return 0;
}


substr

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s="abcdef";
    cout<<s.substr(a,b)<<endl; //标识子串 从s[a]开始,往后的b个输出
    cout<<s.substr(a)<<endl; //等同于“cout<<s.substr(a,s.size())<<endl;”
    return 0;
}


字典序
查找

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s="abcdef";
    string t="abcef";
    int flag=(s<t); //-1,0,1
    cout<<flag<<endl;
    return 0;
}


 

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s="alojhoapbcvkkookokqodkowdfirvvejwjjcjeifhncasxxzxf";
    int pos=s.find_first_of("aeiou"); //返回第一个出现的位置
    //同时,还有:s.find_last_of("");
    //int pos=s.find_last_of("aeiou");//返回最后个出现的位置
    cout<<pos<<endl;
    return 0;
}

#include<bits/stdc++.h>
using namespace std;
int main(){
    string s="alojhoapbcvkkookokqodkowdfirvvejwjjcjeifhncasxxzxf";
    int pos=s.find_first_of("aeiou"); //返回第一个出现的位置
    while(1){ //不断把找到的“aeiou”变为‘r’
        s[pos]='r';
        pos=s.find_first_of("aeiou");
        if(pos==-1) break;
    }
    cout<<s<<endl;
    return 0;
}


 更多关于字符串的函数,可咨询:www.cplusplus.com, 本人大力推荐

 加微信群免费答疑,分享资料: 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值