溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++中的String函數(shù)怎么使用

發(fā)布時間:2023-04-19 11:44:53 來源:億速云 閱讀:105 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“C++中的String函數(shù)怎么使用”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強(qiáng),希望這篇“C++中的String函數(shù)怎么使用”文章能幫助大家解決問題。

一. string的構(gòu)造函數(shù)的形式:

string str:生成空字符串

string s(str):生成字符串為str的復(fù)制品

string s(str, strbegin,strlen):將字符串str中從下標(biāo)strbegin開始、長度為strlen的部分作為字符串初值

string s(cstr, char_len):以C_string類型cstr的前char_len個字符串作為字符串s的初值

string s(num ,c):生成num個c字符的字符串

string s(str, stridx):將字符串str中從下標(biāo)stridx開始到字符串結(jié)束的位置作為字符串初值

eg:


    string str1;               //生成空字符串
    string str2("123456789");  //生成"1234456789"的復(fù)制品
    string str3("12345", 0, 3);//結(jié)果為"123"
    string str4("012345", 5);  //結(jié)果為"01234"
    string str5(5, '1');       //結(jié)果為"11111"
    string str6(str2, 2);      //結(jié)果為"3456789"
#include <iostream>
#include <string>
using namespace std;

void test1()
{
    string str1;               //生成空字符串
    string str2("123456789");  //生成"1234456789"的復(fù)制品
    string str3("12345", 0, 3);//結(jié)果為"123"
    string str4("0123456", 5);  //結(jié)果為"01234"
    string str5(5, '1');       //結(jié)果為"11111"
    string str6(str2, 2);      //結(jié)果為"3456789"

    cout<<"str2:"<<str2<<endl;
    cout<<"str3:"<<str3<<endl;
    cout<<"str4:"<<str4<<endl;
    cout<<"str5:"<<str5<<endl;
    cout<<"str6:"<<str6<<endl;
}

int main()
{
    test1();
    return 0;
}

C++中的String函數(shù)怎么使用

二. string的大小和容量::

1. size()和length():返回string對象的字符個數(shù),他們執(zhí)行效果相同。

2. max_size():返回string對象最多包含的字符數(shù),超出會拋出length_error異常

3. capacity():重新分配內(nèi)存之前,string對象能包含的最大字符數(shù)
void test2()
{
    string s("1234567");
    cout << "size=" << s.size() << endl;
    cout << "length=" << s.length() << endl;
    cout << "max_size=" << s.max_size() << endl;
    cout << "capacity=" << s.capacity() << endl;

}

C++中的String函數(shù)怎么使用

三. string的字符串比較:

1. C ++字符串支持常見的比較操作符(>,>=,<,<=,==,!=),甚至支持string與C-string的比較(如 str<”hello”)。  
在使用>,>=,<,<=這些操作符的時候是根據(jù)“當(dāng)前字符特性”將字符按字典順序進(jìn)行逐一得 比較。字典排序靠前的字符小,  
比較的順序是從前向后比較,遇到不相等的字符就按這個位置上的兩個字符的比較結(jié)果確定兩個字符串的大小(前面減后面)
同時,string (“aaaa”) <string(aaaaa)。    

2. 另一個功能強(qiáng)大的比較函數(shù)是成員函數(shù)compare()。他支持多參數(shù)處理,支持用索引值和長度定位子串來進(jìn)行比較。 
  他返回一個整數(shù)來表示比較結(jié)果,返回值意義如下:0:相等 1:大于 -1:小于 (A的ASCII碼是65,a的ASCII碼是97)
void test3()
{
    // (A的ASCII碼是65,a的ASCII碼是97)
    // 前面減去后面的ASCII碼,>0返回1,<0返回-1,相同返回0
    string A("aBcd");
    string B("Abcd");
    string C("123456");
    string D("123dfg");

    // "aBcd" 和 "Abcd"比較------ a > A
    cout << "A.compare(B):" << A.compare(B)<< endl;                          // 結(jié)果:1

    // "cd" 和 "Abcd"比較------- c > A
    cout << "A.compare(2, 3, B):" <<A.compare(2, 3, B)<< endl;                // 結(jié)果:1

    // "cd" 和 "cd"比較 
    cout << "A.compare(2, 3, B, 2, 3):" << A.compare(2, 3, B, 2, 3) << endl;  // 結(jié)果:0


    // 由結(jié)果看出來:0表示下標(biāo),3表示長度
    // "123" 和 "123"比較 
    cout << "C.compare(0, 3, D, 0, 3)" <<C.compare(0, 3, D, 0, 3) << endl;    // 結(jié)果:0

}

C++中的String函數(shù)怎么使用

四. string的插入:push_back() 和 insert()

void  test4()
{
    string s1;

    // 尾插一個字符
    s1.push_back('a');
    s1.push_back('b');
    s1.push_back('c');
    cout<<"s1:"<<s1<<endl; // s1:abc

    // insert(pos,char):在制定的位置pos前插入字符char
    s1.insert(s1.begin(),'1');
    cout<<"s1:"<<s1<<endl; // s1:1abc
}

C++中的String函數(shù)怎么使用

五、string拼接字符串:append() & + 操作符

void test5()
{
    // 方法一:append()
    string s1("abc");
    s1.append("def");
    cout<<"s1:"<<s1<<endl; // s1:abcdef

    // 方法二:+ 操作符
    string s2 = "abc";
    /*s2 += "def";*/
    string s3 = "def";
    s2 += s3.c_str();
    cout<<"s2:"<<s2<<endl; // s2:abcdef
}

C++中的String函數(shù)怎么使用

六、 string的遍歷:借助迭代器 或者 下標(biāo)法

void test6()
{
    string s1("abcdef"); // 調(diào)用一次構(gòu)造函數(shù)

    // 方法一: 下標(biāo)法

    for( int i = 0; i < s1.size() ; i++ )
    {
        cout<<s1[i];
    }
    cout<<endl;

    // 方法二:正向迭代器

    string::iterator iter = s1.begin();
    for( ; iter < s1.end() ; iter++)
    {
        cout<<*iter;
    }
    cout<<endl;

    // 方法三:反向迭代器
    string::reverse_iterator riter = s1.rbegin();
    for( ; riter < s1.rend() ; riter++)
    {
        cout<<*riter;
    }
    cout<<endl;
}

C++中的String函數(shù)怎么使用

七、 string的刪除:erase()

1. iterator erase(iterator p);//刪除字符串中p所指的字符

2. iterator erase(iterator first, iterator last);//刪除字符串中迭代器

區(qū)間[first,last)上所有字符

3. string& erase(size_t pos = 0, size_t len = npos);//刪除字符串中從索引

位置pos開始的len個字符

4. void clear();//刪除字符串中所有字符
void test6()
{
    string s1 = "123456789";


    // s1.erase(s1.begin()+1);              // 結(jié)果:13456789
    // s1.erase(s1.begin()+1,s1.end()-2);   // 結(jié)果:189
    s1.erase(1,6);                       // 結(jié)果:189
    string::iterator iter = s1.begin();
    while( iter != s1.end() )
    {
        cout<<*iter;
        *iter++;
    }
    cout<<endl;

}

八、 string的字符替換:

1. string& replace(size_t pos, size_t n, const char *s);//將當(dāng)前字符串

從pos索引開始的n個字符,替換成字符串s

2. string& replace(size_t pos, size_t n, size_t n1, char c); //將當(dāng)前字符串從pos索引開始的n個字符,替換成n1個字符c

3. string& replace(iterator i1, iterator i2, const char* s);//將當(dāng)前字符串[i1,i2)區(qū)間中的字符串替換為字符串s
void test7()
{
    string s1("hello,world!");

    cout<<s1.size()<<endl;                     // 結(jié)果:12
    s1.replace(s1.size()-1,1,1,'.');           // 結(jié)果:hello,world.

    // 這里的6表示下標(biāo)  5表示長度
    s1.replace(6,5,"girl");                    // 結(jié)果:hello,girl.
    // s1.begin(),s1.begin()+5 是左閉右開區(qū)間
    s1.replace(s1.begin(),s1.begin()+5,"boy"); // 結(jié)果:boy,girl.
    cout<<s1<<endl;
}

九、 string的大小寫轉(zhuǎn)換:tolower()和toupper()函數(shù) 或者 STL中的transform算法

方法一:使用C語言之前的方法,使用函數(shù),進(jìn)行轉(zhuǎn)換

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s = "ABCDEFG";

    for( int i = 0; i < s.size(); i++ )
    {
        s[i] = tolower(s[i]);
    }

    cout<<s<<endl;
    return 0;
}

方法二:通過STL的transform算法配合的toupper和tolower來實現(xiàn)該功能

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    string s = "ABCDEFG";
    string result;

    transform(s.begin(),s.end(),s.begin(),::tolower);
    cout<<s<<endl;
    return 0;
}

十、 string的查找:find

1. size_t find (constchar* s, size_t pos = 0) const;

  //在當(dāng)前字符串的pos索引位置開始,查找子串s,返回找到的位置索引,

    -1表示查找不到子串

2. size_t find (charc, size_t pos = 0) const;

  //在當(dāng)前字符串的pos索引位置開始,查找字符c,返回找到的位置索引,

    -1表示查找不到字符

3. size_t rfind (constchar* s, size_t pos = npos) const;

  //在當(dāng)前字符串的pos索引位置開始,反向查找子串s,返回找到的位置索引,

    -1表示查找不到子串

4. size_t rfind (charc, size_t pos = npos) const;

  //在當(dāng)前字符串的pos索引位置開始,反向查找字符c,返回找到的位置索引,-1表示查找不到字符

5. size_tfind_first_of (const char* s, size_t pos = 0) const;

  //在當(dāng)前字符串的pos索引位置開始,查找子串s的字符,返回找到的位置索引,-1表示查找不到字符

6. size_tfind_first_not_of (const char* s, size_t pos = 0) const;

  //在當(dāng)前字符串的pos索引位置開始,查找第一個不位于子串s的字符,返回找到的位置索引,-1表示查找不到字符

7. size_t find_last_of(const char* s, size_t pos = npos) const;

  //在當(dāng)前字符串的pos索引位置開始,查找最后一個位于子串s的字符,返回找到的位置索引,-1表示查找不到字符

8. size_tfind_last_not_of (const char* s, size_t pos = npos) const;

 //在當(dāng)前字符串的pos索引位置開始,查找最后一個不位于子串s的字符,返回找到的位置索引,-1表示查找不到子串
void test8()
{
    string s("dog bird chicken bird cat");

    //字符串查找-----找到后返回首字母在字符串中的下標(biāo)

    // 1. 查找一個字符串
    cout << s.find("chicken") << endl;        // 結(jié)果是:9

    // 2. 從下標(biāo)為6開始找字符'i',返回找到的第一個i的下標(biāo)
    cout << s.find('i',6) << endl;            // 結(jié)果是:11

    // 3. 從字符串的末尾開始查找字符串,返回的還是首字母在字符串中的下標(biāo)
    cout << s.rfind("chicken") << endl;       // 結(jié)果是:9

    // 4. 從字符串的末尾開始查找字符
    cout << s.rfind('i') << endl;             // 結(jié)果是:18-------因為是從末尾開始查找,所以返回第一次找到的字符

    // 5. 在該字符串中查找第一個屬于字符串s的字符
    cout << s.find_first_of("13br98") << endl;  // 結(jié)果是:4---b

    // 6. 在該字符串中查找第一個不屬于字符串s的字符------先匹配dog,然后bird匹配不到,所以打印4
    cout << s.find_first_not_of("hello dog 2006") << endl; // 結(jié)果是:4
    cout << s.find_first_not_of("dog bird 2006") << endl;  // 結(jié)果是:9

    // 7. 在該字符串最后中查找第一個屬于字符串s的字符
    cout << s.find_last_of("13r98") << endl;               // 結(jié)果是:19

    // 8. 在該字符串最后中查找第一個不屬于字符串s的字符------先匹配t--a---c,然后空格匹配不到,所以打印21
    cout << s.find_last_not_of("teac") << endl;            // 結(jié)果是:21

}

十一、 string的排序:sort(s.begin(),s.end())

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

void test9()
{
    string s = "cdefba";
    sort(s.begin(),s.end());
    cout<<"s:"<<s<<endl;     // 結(jié)果:abcdef
}

十二、 string的分割/截取字符串:strtok() & substr()

strtok():分割字符串

void test10()
{
    char str[] = "I,am,a,student; hello world!";

    const char *split = ",; !";
    char *p2 = strtok(str,split);
    while( p2 != NULL )
    {
        cout<<p2<<endl;
        p2 = strtok(NULL,split);
    }
}

C++中的String函數(shù)怎么使用

void test11()
{
    string s1("0123456789");
    string s2 = s1.substr(2,5); // 結(jié)果:23456-----參數(shù)5表示:截取的字符串的長度
    cout<<s2<<endl;
}

關(guān)于“C++中的String函數(shù)怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI