我正在尝试编写一些代码,以使单词不断添加到名为sTable的字符数组中,并以\ 0分隔。sTable的最终内容如下所示:
“ word \ 0int \ 0paper \ 0mushroom \ 0etc \ 0”
我的第一个想法是将单词读入一个单独的字符数组tempWord并将它们连接在一起,但是,我如何能够在它们之间添加\ 0并使sTable ass保留为最终数组?我对C不太熟悉,在此先感谢您的帮助!
您可以通过在要接收单词的单词数组中保留下一个位置的指针来实现此目的。add_word()
下面的函数将指针指向char
s和字符串数组中的某个位置。添加wrd
到以开始next
的位置后,返回指向空终止符后的位置的指针。的next
指针初始化为给定的字符阵列中的第一个位置的地址words[]
。请记住,这里没有错误检查,因此调用者负责确保字符串适合数组。
#include <stdio.h>
#define MAX_SIZE 1000
char * add_word(char *next, const char *wrd);
int main(void)
{
char words[MAX_SIZE];
char *next = words;
next = add_word(next, "word");
next = add_word(next, "int");
next = add_word(next, "mushroom");
next = add_word(next, "etc");
for (char *ptr = words; ptr < next; ptr++) {
if (*ptr == '\0') {
printf("\\0");
} else {
putchar(*ptr);
}
}
putchar('\n');
return 0;
}
char * add_word(char *next, const char *wrd)
{
while (*wrd != '\0') {
*next++ = *wrd++;
}
*next++ = '\0';
return next;
}
程序输出:
word\0int\0mushroom\0etc\0
这是上述程序的一个版本,已被修改,以便该add_word()
函数获取要添加的单词的起始位置的索引,并返回下一个单词的索引。word_indices[]
还添加了一个数组,以保存添加到的每个单词的起始索引words[]
。
#include <stdio.h>
#define MAX_SIZE 1000
size_t add_word(char *tokens, size_t next, const char *wrd);
int main(void)
{
char words[MAX_SIZE];
size_t word_indices[MAX_SIZE] = { 0 };
size_t next = 0, count = 0;
char *input[4] = { "word", "int", "mushroom", "etc" };
for (size_t i = 0; i < 4; i++) {
next = add_word(words, next, input[i]);
word_indices[++count] = next;
}
/* Show characters in words[] */
for (size_t i = 0; i < next; i++) {
if (words[i] == '\0') {
printf("\\0");
} else {
putchar(words[i]);
}
}
putchar('\n');
/* Print words in words[] */
for (size_t i = 0; i < count; i++) {
puts(&words[word_indices[i]]);
}
return 0;
}
size_t add_word(char *tokens, size_t next, const char *wrd)
{
while (*wrd != '\0') {
tokens[next++] = *wrd++;
}
tokens[next++] = '\0';
return next;
}
程序输出:
word\0int\0mushroom\0etc\0
word
int
mushroom
etc
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句