C - 将字符串添加到现有数组

时间:2015-10-23 00:18:28

标签: c arrays while-loop

我正在尝试将字符串添加到现有数组中,但我有点卡住了。我必须检查* word是否已经在数组中,如果不是,那么我必须将它添加到数组中。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
int insert(char *word, char *Table[], int n)
{
    //char *word is the string to be added, *char Table[] is array of strings
    //int n is the return value, which is the number of elements in *Table[]
    int counter = 0
    while(*Table[counter]) //while at Index counter
    {
        if strcmp((*Table[counter], *word) == 0) //if *word at Index counter is true
        {
            return n; //return the amount of strings in the array
            break; //terminate the while-loop
        else
        {
            counter++; //increment the counter to check the next index
        }
    }
}

所以我希望成功检查* word是否已经在数组中,但如果不是,我该如何添加呢?先谢谢你们。

2 个答案:

答案 0 :(得分:-1)

首先关闭你的地方

if strcmp((*Table[counter], *word) == 0) //if *word at Index counter is true
        {
            return n; //return the amount of strings in the array
            break;

break没用,因为一旦return n函数停止。

其次让我们考虑一下,如果我们从未在*Table[]中找到单词,那么while循环应该最终退出吗?因此,如果我们退出while循环

,我们找不到*word的情况 编辑:您的编译器应该抱怨此函数,因为它可能会退出while循环,然后函数不返回任何内容,但如果您的编译器没有说出需要打开的任何内容,则指定它返回int编译器警告或使用不同的编译器。

尝试类似的东西。这是未经测试的代码,因此您可能仍需要使用它。

while(*Table[counter]) //while at Index counter
    {
        if strcmp((*Table[counter], *word) == 0) //if *word at Index counter is true
        {
            return n; //return the amount of strings in the array
            break; //terminate the while-loop
        else
        {
            counter++; //increment the counter to check the next index
        }
    }
    *Table[counter] = *word; //Add word to the next available spot in the array
    return 0;
}//End function

答案 1 :(得分:-2)

请尝试这个,它运行正常并添加到字符串数组。    对于初学者来说,最好从简单开始。    在这里,我们从5个长度为99的字符串开始    我给你留下了一些工作要做。玩得开心。

#include <stdio.h>
#include <stdlib.h>

#define MAXSTRINGS 5
#define LENSTRING 99

int insert( char word[], char Table[][99] )  // removed n , could not understand the need.
{
  int counter = 0;

  while ( counter < MAXSTRINGS && strlen( Table[counter] ) )    //while at Index counter and string not empty
  {

    if ( strcmp( Table[counter], word ) == 0 )  //if string was found
    {
      return counter;           //return string position  in array of strings
      break;            //terminate the while-loop
    }
    else
    {
      counter++;        //increment the counter to check the next index
    }

  }// endwhile
  strcpy( Table[counter], word );
  printf( "\n added at %d", counter );
  return(counter);
}

int main(  )
{
  char Table[MAXSTRINGS][LENSTRING];
  int i = 0;
  int answer = 0;

  for ( i = 0; i < MAXSTRINGS; i++ )
    memset( Table[i], '\0', LENSTRING );

  strcpy( Table[0], "a test" );
  strcpy( Table[1], "another test" );

  answer = insert( "test", Table);
  if ( !answer )
    printf( "\n already in file" );
  else
    printf( "\nadded record to position %d in array ", answer );

  getchar(  );

}