C语言如何选取指定字符串并避免大量if实现多字符串交换
问题分析与实现方案
现有代码的核心问题
- 第一,swap函数逻辑无效:C语言是值传递,当前你传入的
char*类型参数是指针的副本,函数内部交换的只是临时形参的地址,不会修改外部原字符串的实际指向或者内容,操作完全不生效。 - 第二,大量if判断冗余:不需要枚举所有交换组合,只需要把四个字符串的地址存入数组,用用户输入的序号直接索引对应元素即可。
优化实现方案
实现思路
- 把四个字符串存入数组,用户输入的14序号可以直接映射为数组的03下标,无需判断任意两个选择的组合
- 修正交换逻辑,根据你的使用场景选择交换字符串内容,或者交换字符串指针。
完整示例代码
#include <stdio.h> #include <string.h> // 方案1:字符串存储在栈数组中,直接交换内容,适用于需要修改字符串内容的场景 void swap_string_content(char *str1, char *str2, int max_buf_len) { char temp[max_buf_len]; strcpy(temp, str1); strcpy(str1, str2); strcpy(str2, temp); } // 方案2:仅交换指针指向,适用于字符串为常量、不需要修改内容的场景,性能更高 void swap_string_ptr(char **str1, char **str2) { char *temp = *str1; *str1 = *str2; *str2 = temp; } void swap_menu(){ // 定义数组存储4个字符串,直接用下标索引 char str_arr[4][20] = { "This is string 1", "This is string 2", "This is string 3", "This is string 4" }; int choice1, choice2; printf("Which string do you want to swap: "); scanf("%i", &choice1); printf("Enter string you want to swap with: "); scanf("%i", &choice2); // 简单合法性校验 if (choice1 < 1 || choice1 >4 || choice2 <1 || choice2>4 || choice1 == choice2) { printf("Invalid input\n"); return; } // 无任何组合判断,直接用输入序号取对应下标元素交换 swap_string_content(str_arr[choice1-1], str_arr[choice2-1], 20); // 验证交换结果 for(int i=0; i<4; i++) { printf("String %d: %s\n", i+1, str_arr[i]); } /* 如果你要使用指针交换方案,替换上面的代码即可: char *str_ptr_arr[4] = { "This is string 1", "This is string 2", "This is string 3", "This is string 4" }; swap_string_ptr(&str_ptr_arr[choice1-1], &str_ptr_arr[choice2-1]); for(int i=0; i<4; i++) { printf("String %d: %s\n", i+1, str_ptr_arr[i]); } */ }
内容的提问来源于stack exchange,提问作者Erika
相关产品推荐
相关产品推荐

