C++ string详解(四)

2011-04-21 16:47:25 · 作者: · 浏览: 3961
<<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