关于在C++中访问字符串字母

Regarding accessing letters of strings in C++

本文关键字:字符串 访问 C++      更新时间:2023-10-16
#include <iostream>
#include <string>
using namespace std;
int main() {
    int n;cin>>n;//entering number of string to be inputed
    string a[n];//declaring an array of type string
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    for(int i=0;i<n;i++){
        cout<<a[i]<<endl;
    }
    //for manipulating letters of strings
    cout<<a[0][1];
    return 0;
}

要访问字符串的元素,我们应该将结果输出为多维数组。这似乎有点违反直觉。有人可以解释这是正确的方式吗?

Input
2
asfdsf
asfdsafd
Output
asfdsf
asfdsafd
s

字符串是一个字符数组。 因此,字符串数组是字符数组的数组。 要访问第 i 个字符串中的第 j 个字符,请使用 a[i][j]

您不能声明:

    string a[n]; //declaring an array of type string

为什么?

ISO C++ forbids variable length array ‘a’ 

相反,您应该使用string vector.push_back()您添加的每个新字符串,例如

#include <iostream>
#include <string>
#include <vector>
int main (void) {
    int n = 0;
    std::cout << "enter the number of strings: ";
    std::cin >> n;
    if (n < 1) {
        std::cerr << "error: invalid number of strings.n";
        return 1;
    }
    std::vector <std::string> a;  // vector of strings
    for (int i = 0; i < n; i++) {   /* read each string */
        std::string tmp;
        std::cin >> tmp;            /* into a temp string */
        if (!std::cin.eof() && !std::cin.fail())    /* validate read */
            a.push_back(tmp);       /* add string to vector */
        /* output string and first character using indexes */
        std::cout << "string[" << i << "]: " << a[i] << "  (a[" << i 
                    << "][0]: " << a[i][0] << ")n";
    }
}

示例使用/输出

$ ./bin/stringindex
enter the number of strings: 4
My
string[0]: My  (a[0][0]: M)
Dog
string[1]: Dog  (a[1][0]: D)
Has
string[2]: Has  (a[2][0]: H)
Fleas!
string[3]: Fleas!  (a[3][0]: F)

仔细看看,如果您有任何问题,请告诉我。