使用結構體類型實現字符串順序表的基本操作:輸入字符串、顯示字符串、查找字符、統計長度、退出程序。菜單驅動交互模式。
typedef struct String {
char string[100];
} SqList;
使用固定長度字符數組模擬順序表,結構體封裝便於傳遞。
void Creat_List(SqList *L) {
printf("Input a string: ");
scanf("%s", L->string);
}
void Print(SqList *L) {
for (int i = 0; L->string[i] != '\0'; i++) {
printf("%2c", L->string[i]);
}
printf("\n");
}
void LoopUp(SqList *L) {
printf("Find a character: ");
char ch;
getchar(); // 吸收換行符
scanf("%c", &ch);
int found = 0;
for (int i = 0; L->string[i] != '\0'; i++) {
if (ch == L->string[i]) {
found = 1;
break;
}
}
if (found) printf("%3c is in the list\n", ch);
else printf("%3c is not in the list\n", ch);
}
int Count(SqList *L) {
int len = 0;
while (L->string[len] != '\0') len++;
return len;
}
int main() {
SqList L;
int choice;
while (1) {
printf("-------------------MENU-------------------\n");
printf("1. String to list\n");
printf("2. Show the list\n");
printf("3. LoopUp\n");
printf("4. Count\n");
printf("5. Exit\n");
printf("Choose the item(1~5): ");
scanf("%d", &choice);
switch (choice) {
case 1: Creat_List(&L); break;
case 2: printf("List: "); Print(&L); break;
case 3: LoopUp(&L); break;
case 4: printf("String length: %d\n", Count(&L)); break;
case 5: exit(0);
default: printf("Error\n");
}
}
return 0;
}
-------------------MENU-------------------
1. String to list
2. Show the list
3. LoopUp
4. Count
5. Exit
Choose the item(1~5): 1
Input a string: abcdefg
-------------------MENU-------------------
Choose the item(1~5): 2
List: a b c d e f g
-------------------MENU-------------------
Choose the item(1~5): 3
Find a character: a
a is in the list
-------------------MENU-------------------
Choose the item(1~5): 4
String length: 7
fgets 替代 scanf 支持空格輸入