设为首页 加入收藏

TOP

C++ string详解(四)
2011-04-21 16:47:25 来源:CSDN 作者: 【 】 浏览:3936
Tags:string 详解
<<s<<endl;

    cin.get();

}

14)

//clear() 删除全部字符

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s = "abcdefg";

    cout<<s.length()<<endl;

    s.clear();

    cout<<s.length()<<endl;

    //使用earse方法变相全删除

    s = "dkjfd";

    cout<<s.length()<<endl;

    s.erase(0,s.length());

    cout<<s.length()<<endl;

    cin.get();

}

15)

//replace() 替换字符

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s = "abcdefg";

    s.replace(2,3,"!!!!!");//从索引2开始3个字节的字符全替换成"!!!!!"

    cout<<s<<endl;

    cin.get();

}

16)

//==,!=,<,<=,>,>=,compare()  比较字符串

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s1 = "abcdefg";

    string s2 = "abcdefg";   

    if (s1==s2)cout<<"s1 == s2"<<endl;

    else cout<<"s1 != s2"<<endl;

    if (s1!=s2)cout<<"s1 != s2"<<endl;

    else cout<<"s1 == s2"<<endl;

    if (s1>s2)cout<<"s1 > s2"<<endl;

    else cout<<"s1 <= s2"<<endl;

    if (s1<=s2)cout<<"s1 <= s2"<<endl;

    else cout<<"s1 > s2"<<endl;

    cin.get();

}

17)

//size(),length()  返回字符数量

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s = "abcdefg";

    cout<<s.size()<<endl;

    cout<<s.length()<<endl;

    cin.get();

}

18)

//max_size() 返回字符的可能最大个数

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s = "abcdefg";

    cout<<s.max_size()<<endl;

    cin.get();

}

19)

//empty()  判断字符串是否为空

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s ;

    if (s.empty())

        cout<<"s 为空."<<endl;

    else

        cout<<"s 不为空."<<endl;

    s = s + "abcdefg";

    if (s.empty())

        cout<<"s 为空."<<endl;

    else

        cout<<"s 不为空."<<endl;

    cin.get();

}

20)

// [ ], at() 存取单一字符

#include <string>

#include <iostream>

using namespace std;

void main()

{

    string s = "abcdefg1111";

    cout<<"use []:"<<endl;

    for(int i=0; i<s.length(); i++)

    {

        cout<<s[i]<<endl;

    }

    cout&l

首页 上一页 1 2 3 4 5 下一页 尾页 4/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++ string erase函数的使用 下一篇函数指针和指针函数