一、使用string数组存储文本数据
在C++中,可以使用string类型的数组来存储文本数据。
#include <iostream>
#include <string>
using namespace std;
int main()
{
    const int SIZE = 5;
    string texts[SIZE];
    for(int i=0; i<SIZE; i++)
    {
        cout << "请输入第" << i+1 << "个字符串: ";
        cin >> texts[i];
    }
    cout << "你输入的字符串为: " << endl;
    for(int i=0; i<SIZE; i++)
    {
        cout << texts[i] << endl;
    }
    return 0;
}
上述代码中,定义了一个长度为5的string数组,循环读取用户输入的字符串并存储到数组中,最后循环输出存储的字符串。
二、使用string类的成员函数操作字符串
除了使用数组存储字符串,C++中的string类还提供了丰富的成员函数来操作字符串。
1. size()
size()函数返回字符串的长度。
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string text = "Hello world!";
    cout << "字符串的长度为: " << text.size() << endl;
    return 0;
}
2. substr()
substr()函数可以截取字符串的一部分。
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string text = "Hello world!";
    string subtext = text.substr(0, 5);
    cout << "截取的字符串为: " << subtext << endl;
    return 0;
}
3. append()
append()函数可以在字符串的末尾添加一个字符串。
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string text = "Hello ";
    text.append("world!");
    cout << "拼接后的字符串为: " << text << endl;
    return 0;
}
4. replace()
replace()函数可以替换字符串的一部分。
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string text = "Hello world!";
    text.replace(6, 5, "there");
    cout << "替换后的字符串为: " << text << endl;
    return 0;
}
三、使用STL算法操作string数组
C++ STL中的算法库可以方便地对string数组进行排序、查找等操作。
1. sort()
sort()函数可以对string数组进行升序排序。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    const int SIZE = 5;
    string texts[SIZE] = {"apple", "banana", "orange", "grape", "pear"};
    sort(texts, texts+SIZE);
    cout << "排序后的字符串为: " << endl;
    for(int i=0; i<SIZE; i++)
    {
        cout << texts[i] << endl;
    }
    return 0;
}
2. find()
find()函数可以在string数组中查找指定字符串。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    const int SIZE = 5;
    string texts[SIZE] = {"apple", "banana", "orange", "grape", "pear"};
    string str = "banana";
    if(find(texts, texts+SIZE, str) != texts+SIZE)
    {
        cout << "找到了字符串 " << str << endl;
    }
    else
    {
        cout << "没找到字符串 " << str << endl;
    }
    return 0;
}
3. count()
count()函数可以计算string数组中指定字符串出现的次数。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
    const int SIZE = 5;
    string texts[SIZE] = {"apple", "banana", "orange", "banana", "pear"};
    string str = "banana";
    int count = 0;
    for(int i=0; i<SIZE; i++)
    {
        if(texts[i] == str)
        {
            count++;
        }
    }
    cout << "字符串 " << str << " 出现了 " << count << " 次" << endl;
    return 0;
}
四、总结
使用C++ string数组存储和操作文本数据,可以通过使用string类型的数组存储文本数据,使用string类的成员函数操作字符串,以及使用STL算法操作string数组等方式来实现。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/286133.html
微信扫一扫 
支付宝扫一扫