如何在C++中有效地使用字符串data_type

How do effectively use the string data_type in C++?

本文关键字:字符串 data type 有效地 C++      更新时间:2023-10-16

我试着制作这个小程序,它接受输入并检查元音。如果有元音,它会将它们附加到字符串中,并返回字符串的大小。

我唯一的问题是我无法使用字符串使其工作。使用字符数组的主要区别是什么?我可以使用类似的东西让程序工作

char entered[128];
//and then
char exceptions[11] = "aeiouAEIOU";

**关于上述数组的快速问题。当我将缓冲区分配给"exceptions"时,它必须是11,否则编译器将出错。我必须手动解释NULL终止部分吗?

如果我做了这样的事情:

if(cPtrI[i] == 'a'){

我收到一个错误,说明未知运算符'=='??我以为"=="是一个检查运算符,而"="则是一个赋值运算符?

no match for 'operator==' in '*((+(((unsigned int)i) * 4u)) + cPtrI) == 'a''|

而且,如果我做了这样的事情:(一开始我认为这是正确的)

if(*cPtrI[i] == *cPtrJ[j]){

我得到了与上面相同的错误,但引用了未知运算符*:

no match for 'operator*' in '**((+(((unsigned int)i) * 4u)) + cPtrI)'|
no match for 'operator*' in '**((+(((unsigned int)j) * 4u)) + cPtrJ)'|

我以为*运算符实际上说的是指针指向的地址"what is at"。

所以,上面的内容应该是:

If(What is at index I of string 'a' EQUALS What is at index J of string 'exceptions'){
then ..

这个有什么帮助吗?我在C++之前学过一点C,所以也许这就是我困惑的原因。据我所知,上面的代码会比较它们所指向的字符/变量的地址。*表示"what is at",而仅仅放置指针名称就会表示指针所持有的值(即所指向的变量的地址)。使用&ptrName应该是指针本身的地址,对吗?我哪里错了?

#include <iostream>
#include <string>
int vowelCheck(std::string a);
int main()
{using namespace std;
    string eString;
    cout << "Enter a string: ";
        cin >> eString;
    cout << "There were " << vowelCheck(eString) << " vowels in that string.";
    return 0;
}
int vowelCheck(std::string a)
{using namespace std;
    string exceptions = "aeiouAEIOU";
    string vowels;
    string *cPtrI = &a;
    string *cPtrJ = &exceptions;
    for(int i = 0; i < a.size(); i++){
        cout << i <<"in";
        for(int j = 0; j < 10; j++){
            cout << j << "jn";
           // cout << cPtrJ[j];
            if(cPtrI[i] == cPtrJ[j]){ //if index of A equal index of J then
                cout << "Added: " << cPtrJ[j];
                vowels.append(cPtrJ[j]); // append that vowel to the string 'vowels'
                break;
            }
        }
    }
    return vowels.size();
}

使用上面列出的调试工具,程序将只递增j=8,然后停止。此外,如果我输入一个类似AEIOU的初始字符串,它将字符串遍历j=8。因此,它没有看到等效的字符。

我用字符串做错了什么?

忘记指针

string *cPtrI = &a;
string *cPtrJ = &exceptions;
// ...
if(cPtrI[i] == cPtrJ[j]){ //if index of A equal index of J then

cPtrI[i]*(cPtrI + i)相同,后者将索引到string的数组中。

这就是cPtrI[i] == 'a'不编译的原因。cPtrI[i]的类型为std::string&(记住,它正在索引到一个不存在的std::string数组中),而'a'是一个char。你无法将两者进行比较。

std::string有自己的索引运算符。只是不要使用毫无意义的指针,它只是有效的

if(a[i] == exceptions[j]){

您似乎在计算字符串中元音的数量。让我们使用count_if来实现这一点,而不是手动编写for循环并构建字符串。计划是创建一个函数对象,该对象可以检测字符是否为元音,然后使用count_if来计算字符串中元音字符的数量:

struct VowelFinder
{
    bool operator()(char c)
    {
        std::string vowels = "aeiouAEIOU";
        return vowels.find(c) != std::string::npos;
    }
};
int vowelCheck(const std::string& a)
{
    return std::count_if(a.begin(), a.end(), VowelFinder());
}

我已经在评论中回答了您的C相关问题。

至于您对std::string的使用,您实际上是出于某种原因而尝试使用std::string*。不要那样做。只需使用std::string;操作员CCD_ 15过载,使其按原样工作。目前,您将cPtrI视为字符串数组中的一个元素。