首页 > 解决方案 > 用不同大小的元素实现一个字符串数组

问题描述

如何实现不同大小的字符串数组,即数组stringar[4]={"black","red","blue","green"}。另外,如何访问 C++ 中每个元素的单个字母/字符?编辑:这是我在 CPP 中尝试过的。但它为所有输入提供相同的输出(即 0)。代码:

#include <bits/stdc++.h>
using namespace std;
int main()
{   int n,i,j,p,q,f=0,count=0,key,m;
    char s[100][100];
    cin>>n;
    for( i = 0; i < n; i++)
      for (j = 0; j < 100; j++)
        cin >> s[i][j];
      for(i=0;i<n;i++)
        {
            for (j = 0; j < 100; j++) 
            {
                key = s[i][j];
                for (p = i + 1; p < n; p++) 
                {
                    for (q = 0; q < m; q++) 
                    {
                        if (key == s[p][q]) {f = 1;break;}
                        else {f = 0;continue;}
                    }
                }
                if (f == 1)
                    count++;
            }
        }
    cout<<count;        
    return 0;
}

标签: c++string

解决方案


最后,您需要将其想象为具有可变大小的矩阵。

[b][l][a][c][k]

[r][e][d]

[b][l][u][e]

[g][r][e][n]

 std::vector<std::string> stringar;
    stringar.push_back( "black" );
    stringar.push_back( "red" );

    char letter = stringar[ 0 ][ 1 ]; 
    char letter2 = stringar[ 1 ][ 2 ];

letter将在位置 0 的矩阵中的数组的位置 1 中具有字母:

位置 0 中的数组:black。位置 1 中的字母:l

位置 1 中的数组:red. 位置 2 中的字母:d

[b][l][a][c][k]

[r][e][d]

编辑:

正如您在评论中问我的那样,这是一个粗略的实现,因此您可以看到它是如何完成的!(请原谅我printfcout但我无法使用它。

int rows = 4; //black, red, blue, green ==> 4 elements
    int cols[4] = { 5, 3, 4, 5 }; // 5 letters for black, 3 letters for red, etc.
    int** matrix = new int*[rows];
    for (int i = 0; i < rows; ++i)
        matrix[i] = new int[cols[i]];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols[i];j++) {
            matrix[i][j] = 0;
            printf("%d", matrix[i][j]);
        }
        printf("\n");
    }

这将显示此输出,这就是您要查找的内容(而不是0s,您需要的任何矿物质)。

00000 (black) 000 (red) 0000 (blue) 00000 (green)

输出:


推荐阅读