如何写一个字符列表?

时间:2018-12-24 18:04:40

标签: c

我正在词典中工作,我需要写一个单词列表,然后将其替换为其他单词。我不久前才开始编码,所以对我的无能为力!

//working 
char word[] = { "hello" };
char replace[] = { "salut" };

//not working 
char word[] = { "hello", "what" };
char replace[] = { "salut", "quoi" };

当我尝试编译第二部分时,我在其中编写了“不起作用”的内容,IDE给了我以下错误:“初始化器值太多”,“初始化器太多”。虽然,“工作”部分按预期工作。

我将等待代码的一些解决方案/建议...预先谢谢!

2 个答案:

答案 0 :(得分:3)

您应该使用指针数组来初始化不起作用的部分。 那应该像char *words[] = {"word1", "word2"} ; 修复了无法正常工作的部分,但是您可以详细说明您的问题

编辑1: 这是示例代码:

#include <stdio.h>
int main(char argc,char *argv[])
{
  char *words[2] = {"test","word"};
  printf("words[1] = %s , words[2] = %s \n", words[0], words[1]);
  return 0;
}

此代码返回输出:

words [1] =测试,words [2] =单词

您可以发布错误消息/您正在使用哪个编译器,哪个平台吗?

Edit2:

由于您将单词作为指针数组,因此如果要使用它,则必须在strstr中对其进行正确检查。

这里是示例:

#include <stdio.h>
int main(int argc, char *argv[]) 
{ 
    char str1[] = "practice makes perfect"; 
    char *str2[2] = {"practice", "perfect"}; 
    char* ptr1; 
    char *ptr2;

    ptr1 = strstr(str1, str2[0]);
    ptr2 = strstr(str1, str2[1]); 


    if (ptr1 != NULL ) { 
        printf("String %s found in %s\n",str2[0], str1); 
    } else
        printf("String not found\n");

    if (ptr2 != NULL) {
        printf("String %s found in %s\n", str2[1], str1); 
    } else
        printf("String not found\n");
    return 0; 
} 

Output:
String practice found in practice makes perfect
String perfect found in practice makes perfect

答案 1 :(得分:0)

所以我假设您想拥有两个包含来自两种不同语言的单词的列表。然后,当给您一些英语输入文本时,您想通过使用列表替换单词来将该文本切换为第二种语言。如果我是对的,请使用@cslrnr之类的指针。

char* english[] = {word1, word2, ...};
char* otherLanguage[] = {word1, word2, ...};