组件
我有一个字符串,例如
字符 block [4][256] = "";
我有一句话
char sentence[256] = "Bob walked his dog";
我还有一个迭代器变量
int pos = 0;
我正在努力实现的目标
我正在尝试将数组 sentence
中的每个单词按顺序分配到二维 block 数组 block
中。
例如,
假设我有这段代码(我自己写的 - 没有按我的计划工作)
for (int x=0; x < ((int)strlen(sentence)); x++)
{
if (sentence[x] == ' ') // not using strcmp at the moment to be more clear
{
++pos; // move to the next word after space
for (int y=0; y < pos; y++) // scan through the word
{
for (int z=0; z < x; z++) // add the word to the array
{
block[y][z] = sentence[z]; // assign the block (!!confusion here!!)
}
}
}
}
我怎么看
我通过处理这个问题来看待它的方式是,我需要先扫描句子,直到遇到一个空格 ' ' 字符,一个空白。遇到这种情况后,我必须重新扫描句子并开始将所有字符添加到该空格 ' ' 的位置到我的 block 数组 block[y][z]
的第一段中, z 是上面 for 语句中的迭代器,y 是遇到的每个空格的位置 + 1。我相信我的主要问题是理解如何分配二维数组。如果有人看到解决这个问题的更好方法,我很乐意听到,谢谢!
我想要的输出
打印完 block[x][256]
的内容后,我希望每个 x 都输出我正在扫描的数组中的每个单词。如果我有这样的东西。
for (int a=0; a < 4; a++)
{
for (int b=0; b < strlen(block[a][]); b++)
{
printf("%s\n", block[a][b]);
}
}
我希望输出为:
block[0][]: Bob
block[1][]: walked
block[2][]: his
block[3][]: dog
任何人都可以帮助我解决这个问题吗?谢谢!
最佳答案
我认为这就是您想要的。
int word_start = 0, word_end = 0, current_word = 0;
for (int x = 0; x < strlen(sentence) + 1; x++)
{
if (sentence[x] == ' ' || sentence[x] == '\0')
{
word_end = x;
int y, z;
for (y = 0, z = word_start; z < word_end; y++, z++)
{
block[current_word][y] = sentence[z];
}
word_start = x + 1;
current_word++;
}
}
这是我用来测试它的程序,如果它不适合你,你想看看我是如何解释你的问题的。
#include <stdio.h>
#include <string.h>
int main (const int argc, char * const argv[])
{
char block[4][256] = {0};
char sentence[256] = "Bob walked his dog";
int word_start = 0, word_end = 0, current_word = 0;
for (int x = 0; x < strlen(sentence) + 1; x++)
{
if (sentence[x] == ' ' || sentence[x] == '\0')
{
word_end = x;
int y, z;
for (y = 0, z = word_start; z < word_end; y++, z++)
{
block[current_word][y] = sentence[z];
}
word_start = x + 1;
current_word++;
}
}
for (int x = 0; x < 4; x++)
{
printf("%s\n", block[x]);
}
}
关于c++ - 如何将二维数组相互分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25635616/