如何使用strcpy删除字符串部分内容,仅保留等号左侧内容?
提取字符串中等号左侧内容的C语言实现
针对你需要处理"Home=London","Country=England","User=John"这组字符串、仅保留=左侧内容的需求,结合strcpy的使用,提供两种可行方案:
方案1:直接修改原字符串(简单高效)
如果允许修改原字符串,不需要额外复制,直接通过截断字符串实现:
#include <stdio.h> #include <string.h> int main() { char strs[3][20] = {"Home=London", "Country=England", "User=John"}; for (int i = 0; i < 3; i++) { // 定位等号位置 char *eq_ptr = strchr(strs[i], '='); if (eq_ptr != NULL) { // 将等号替换为字符串结束符,直接截断 *eq_ptr = '\0'; } } // 输出结果 for (int i = 0; i < 3; i++) { puts(strs[i]); } return 0; }
方案2:用strcpy复制到新缓冲区(不修改原字符串)
如果需要保留原字符串完整,可将左侧内容复制到新缓冲区:
#include <stdio.h> #include <string.h> int main() { const char *src_strs[3] = {"Home=London", "Country=England", "User=John"}; char dest_strs[3][20]; // 存储结果的缓冲区,需确保大小足够 for (int i = 0; i < 3; i++) { char *eq_ptr = strchr(src_strs[i], '='); if (eq_ptr != NULL) { // 临时复制原字符串到临时缓冲区并截断 char temp[20]; strcpy(temp, src_strs[i]); *strchr(temp, '=') = '\0'; // 将截断后的结果复制到目标缓冲区 strcpy(dest_strs[i], temp); } else { // 无等号时直接复制原字符串 strcpy(dest_strs[i], src_strs[i]); } } // 输出结果 for (int i = 0; i < 3; i++) { puts(dest_strs[i]); } return 0; }
注意事项
- 确保缓冲区大小足够,避免因左侧内容过长导致缓冲区溢出
- 需判断
strchr的返回值,避免空指针操作(比如原字符串无等号的情况) - 如果追求更安全的复制,推荐搭配
strncpy使用,但要记得手动添加字符串结束符'\0'
内容的提问来源于stack exchange,提问作者Francesco Totti
相关产品推荐
相关产品推荐

