对于string型甚是周详的用法

本文通过实例演示了C++中字符串的各种操作方法,包括容量、替换、查找等常见功能,并对比了不同方法的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把网上可以找到的一些string的函数、用法用代码的形式敲了一遍

没什么难点,看过了基本就会了

#include<iostream>
#include<string>
#include<cstring>
#include<limits.h>
#include<algorithm>
#include<cstdio>
using namespace std;
int main()
{
    string a="abcdefgh";
    cout<<a<<endl<<endl;
    cout<<"a.capacity() is "<<a.capacity()<<endl<<endl;
    a.erase(2,3);
    cout<<a<<endl<<endl;
    a.erase(2);
    cout<<a<<endl<<endl;
    cout<<"a.capacity() is "<<a.capacity()<<endl<<endl;
    a.replace(2,1,"hahaha! ");
    cout<<a<<endl<<endl;
    cout<<a.length()<<' '<<a.size()<<endl<<endl;
    cout<<"2*a.max_size() is "<<2*a.max_size()<<endl<<endl;
    cout<<"INT_MAX is "<<INT_MAX<<endl<<endl;
    reverse(a.begin(),a.end());
    cout<<a<<endl<<endl;
    a.reserve(1000);
    cout<<"after reserve , the capcity is "<<a.capacity()<<endl<<endl;
    a.assign(10,'K');a.insert(5," best acmer ");
    cout<<a<<endl<<endl;
    a.assign(20,'/');
    cout<<a<<endl<<endl;
    a="look for non-alphabetic characters...";
    cout<<a<<endl<<endl;

    int found;
    found=a.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
    if (found!=string::npos)cout << "First non-alphabetic character is " << a[found]<<" at position " << found<< endl<<endl;
    found=a.find_last_not_of("abcdefghijklmnopqrstuvwxyz ");
    if (found!=string::npos)cout << "Last non-alphabetic character is " << a[found]<<" at position " << found<< endl<<endl;
    found=a.find_first_of("abcdefghijklmnopqrstuvwxyz");
    if (found!=string::npos)cout << "First alphabetic character is " << a[found]<<" at position " << found<< endl<<endl;
    found=a.find_last_of("abcdefghijklmnopqrstuvwxyz");
    if (found!=string::npos)cout << "Last alphabetic character is " << a[found]<<" at position " << found<< endl<<endl;
    found=a.find('a'); 
    if (found!=string::npos)cout << "First a is at position " << found<< endl<<endl;
    found=a.rfind('a'); 
    if (found!=string::npos)cout << "Last a is at position " << found<< endl<<endl;


    a.assign(20,'/'); cout<<a<<endl<<endl;

    a="AAAAA";
    const char *x=a.data(),*y=a.c_str();//?????????? 

    cout<<x<<"   "<<y<<endl;
    if(x[5]=='\0')cout<<"@@@@@"<<"   "; 
    if(y[5]=='\0')cout<<"$$$$$"<<endl;/////string ?????'\0'??β 
    char xx[100];strcpy(xx,a.c_str());
    cout<<xx<<endl<<endl;

    string b;b.assign(20,'/'); cout<<b<<endl<<endl;
    string c(20,'/'); cout<<c<<endl<<endl;

    a="abcdefg";
    cout<<"after assign , the capcity is "<<a.capacity()<<endl<<endl;
    cout<<a[1]<<' '<<a.at(1)<<endl<<endl;

    c+="\n\n";cout<<c;
    c="\n\n"+c;

    a="abcdefg";a.append(13,'/');a.push_back('7');cout<<a<<c;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值