C + +中的char数组访问每个char

时间:2019-03-08 12:04:38

标签: c arrays data-structures struct char

我需要输入n行,每行有1个“字符串”(字符数组)。然后,我想将它们存储在Word结构中并打印每个结构。我需要访问每个“字符串”的第一个和最后一个字符。

这些字符串在每个字符之后始终带有q字母(最后一个字符除外)。 示例:您好-> Hqeqlqlqo

最重要的事情,我还需要调用一个接收“字符串”的函数,然后取消“ q”并将每个字符添加到这个新的结构WordModified中,因此我可以在结束

所以,我的问题是:如何按char访问两个结构的单词?以及如何构建函数以排除'q'并在WordModified结构中连续追加单词的字母。

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAXCHAR 1100


typedef struct {
  char name[1101];
} WordReceived;

typedef struct {
  char name[1101];
} WordModified;


int main(void)
{
  //char input[1101];
  int nrlines, i;

  scanf("Number of lines %d\n", &nrlines);
  WordReceived words[nrlines];
  WordModified wordsMod[nrlines];

  for (i = 0; i < nrlines; ++i)
  {
    printf("String\n");
    scanf("%s\n", words[i].name);
  }

  for (i = 0; i < nrlines; ++i)
  {
    printf("word %d: %s\n", i+1, words[i].name);
    printf("First char: %s\n",  words[i].name[0]);
    printf("Last char: %s\n",  words[i].name[n-1]);
  }

  for (i = 0; i < nrlines; ++i)
  {
    printf("word %d: %s\n", i+1, wordsMod[i].name);
  }

  return 0;
}

1 个答案:

答案 0 :(得分:1)

带有'q'字符的函数非常简单。请记住,我还没有处理单词中包含“ q”字符的情况,您可以对此进行练习。

我对您的代码做了一些修改,您可以看到我的注释。

我不明白您为什么要访问每个单词的第一个和最后一个字符。

#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAXCHAR 1100 //What is for?

void CleanWord(char *word, char* mod_word);

typedef struct {
  char name[1101];
} WordReceived;

typedef struct {
  char name[1101];
} WordModified;


int main(void)
{
  //char input[1101];
  int nrlines, i;

  printf("Number of lines: \n");
  scanf(" %d", &nrlines);
  WordReceived words[nrlines];
  WordModified wordsMod[nrlines];

  memset(words, 0, sizeof(words));      //Initialize the struct
  memset(words, 0, sizeof(wordsMod));   //Initialize the struct

  for (i = 0; i < nrlines; ++i)
  {
    printf("String\n");
    scanf(" %s", words[i].name);
  }


  for (i = 0; i < nrlines; ++i)
  {
    CleanWord(words[i].name, wordsMod[i].name);

    printf("word %d: %s\n", i+1, words[i].name);
    printf("First char: %c\n",  words[i].name[0]);      //your code has %s formating but the variable is signle character

    int n = strlen(words[i].name);  //store the length of string
    printf("Last char: %c\n",  words[i].name[n-1]);
  }

   for (i = 0; i < nrlines; ++i)
   {
    printf("word %d: %s\n", i+1, wordsMod[i].name);
   }

  return 0;
}

/*  This function remove the char 'q' from the 'word' and store the result to 'mod_word'*/
void CleanWord(char* word, char* mod_word)
{
    int i,j = 0;
    int word_size = strlen(word);

    for(i = 0; i < word_size; i++)
    {
        if(word[i] != 'q')
            mod_word[j++] = word[i];
    }
}