[英]Inputting, Searching and Deleting String in an Array in C
是否可以将字符串输入到二维数组中的任何位置?
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]);
}
go 关于此问题的最佳方法是使用指针,因为您可以使用指针算法简单地strcpy
到您选择的目的地。 我不打算在这里解释指针,我只是要向你展示一条你可以做你想做的事情的路径。
我将要向您展示的是您可以根据需要应用和修改的基本代码。 它绝不会考虑所有可能的错误情况。
将输入字符串放入选择的目的地
#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;
}
Output:
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;
}
Output:
index [2][0] = wordsss
index [2][0] =
index [2][4] = sss
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.