Ввод, поиск и удаление строки в массиве в C - PullRequest
0 голосов
/ 18 апреля 2020

Можно ли ввести строку в любое место в двумерном массиве?

char courseName[8][50] = {NULL};

printf("Enter your second course: ");
scanf("%[^\n]s", courseName[2]);

printf("Enter your fourth course: ");
scanf(" %[^\n]s", courseName[4]);

for(int i = 1; i < 9; i++)
{
    printf("Name of the Courses in courseName[i][50] is %s\n", courseName[i]);
}

или удалить строку внутри массива, введя имя строки?

char deleteCourse[50];

printf("Enter the course name to delete the course");
scanf(" %[^\n]s", deleteCourse);

for(int i = 1; i < 9; i++)
{
  if(deleteCourse == courseName[i])
    {
     courseName[i] = {NULL};
    }
 printf("Your edited courses: %s\n", courseName[i]);
}

1 Ответ

1 голос
/ 19 апреля 2020

Наилучшим способом для go было бы использование указателей, поскольку вы могли бы просто strcpy по своему выбору, используя арифметику указателей c. Я не собираюсь объяснять здесь указатели, я просто покажу вам путь, по которому вы можете пойти, чтобы сделать то, что вы хотите сделать.

То, что я собираюсь показать вам, просто код кости, который вы можете применять и изменять в соответствии с вашими потребностями. Он ни в коем случае не учитывает все возможные случаи ошибок.

Поместите входную строку в выбранный пункт назначения

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

int main(int argc, char *argv[]){

    /* Variables */
    char **courseName;
    int i;

    /* Allocate memory to make courseName look like: courseName[4][100] */ 
    /* I assume the memory allocated properly, but you need to check that */
    courseName = malloc(sizeof(char*) * 4);
    for(i = 0; i < 4; i++){
        courseName[i] = malloc(100);
    }

    /* Copy string to your destination of choice using pointer arithmatic */
    strcpy(courseName[2] + 50, "word");

    /* Printing at different locations to show results */
    printf("index [1][0]   = %s\n", courseName[1]);
    printf("index [2][0]   = %s\n", courseName[2]);
    printf("index [2][50]  = %s\n", courseName[2] + 50);
    printf("index [2][51]  = %s\n", courseName[2] + 51);

    return 0;
}

Вывод:

index [1][0]   = 
index [2][0]   = 
index [2][50]  = word
index [2][51]  = ord

Удаление строки из двумерного массива

Примечание: приведенный ниже код предполагает, что слово имеет индекс [i][0], где i - массив, в котором слово найдено. Поскольку вы не указываете, что именно вам нужно, я предполагаю, что после прочтения вашего вопроса это должно быть в порядке. Тем не менее, вы можете изменить в соответствии с вашими потребностями.

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

int main(int argc, char *argv[]){

    /* Variables  */
    char **courseName, deleteWord[10], *result;
    int i, arrayNum;

    /* Allocate memory to make courseName look like: courseName[4][100] */
    courseName = malloc(sizeof(char*) * 4);
    for(i = 0; i < 4; i++){
        courseName[i] = malloc(100);
    }

    /* Place a word into the array at a random location for the sake of the example */
    strcpy(courseName[2], "word");
    printf("index [2][0]  = %s\n", courseName[2]);

    /* The worrd we want to delete (can be a user input if you want) */
    strcpy(deleteWord, "word");

    /* Loop through the different arrays */
    for(i = 0; i < 4; i++){
        if( (result = strstr(courseName[i], deleteWord)) != NULL ){ /* use strstr() see if the word want to delete exists */
            arrayNum = i; /* Get the array that the word is in (in this case courseName[2]) */
        }
    }

    /* Empty the array at the location where the word is */
    memset(courseName[arrayNum], 0, strlen(deleteWord));

    /* "word" is deleted */
    printf("index [2][0]  = %s\n", courseName[2]);

    /* but "sss" still exists */
    printf("index [2][4]  = %s\n", courseName[2] + 4);
    return 0;
}

Вывод:

index [2][0]  = wordsss
index [2][0]  = 
index [2][4]  = sss
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...