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

问题描述 投票:-1回答:1

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

这些字符串在每个char之后总是有q个字母(除了最后一个)。示例:Hello - > 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;
}
c arrays data-structures struct char
1个回答
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];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.