c - 单独打印两个绑定在一起的小字符串的最有效方法
问题描述
故事:大弦aaa&bbb
是由两个小弦组成的,大弦中两个小弦之间的隔开就是&
符号。
任务:使用最有效的方法分别打印第一个和第二个小字符串。
代码 :
char big_str[8] = "aaa&bbb";
期望的输出:
aaa
bbb
解决方案
最简单的方法是使用字段宽度和'.'
修饰符作为"%s"
格式说明符printf
和几个指针,例如
#include <stdio.h>
#include <string.h>
int main (void) {
char big_str[] = "aaa&bbb",
*p = strchr (big_str, '&'),
*ep = p + 1;
if (p)
printf ("%.*s\n%s\n", (int)(p - big_str), big_str, ep);
return 0;
}
示例使用/输出
$ ./bin/splitand
aaa
bbb
将值分成单独的字符串
要实际分离这些值,您可以以完全相同的方式处理它,除了不是简单地打印输出,而是分配存储空间来保存每个字符串并将所需的字符复制到每个新的内存块。然后你可以以任何你喜欢的方式使用单独的字符串,例如
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
char big_str[] = "aaa&bbb",
*p = strchr (big_str, '&'),
*first, *second; /* pointers to allocate to hold first/second */
if (p) { /* validate '&' located */
char *ep = p + 1; /* ep now points to next char after '&' */
if (!(first = malloc (ep - big_str))) { /* allocate/validate first */
perror ("malloc-first");
return 1;
}
memcpy (first, big_str, p - big_str); /* memcpy to first */
first[p - big_str] = 0; /* nul-terminate */
if (!(second = malloc (strlen(ep) + 1))) { /* allocate second */
perror ("malloc-second");
return 1;
}
strcpy (second, ep); /* strcpy is fine here */
printf ("first : %s\nsecond : %s\n", first, second);
free (first); /* don't forget to free what you allocate */
free (second);
}
}
示例使用/输出
$ ./bin/splitanddyn
first : aaa
second : bbb
如果您还有其他问题,请告诉我。
推荐阅读
- c++ - 使用 OpenCV / C++ 设置树莓相机模式
- ios - navigationItem.leftBarButton 没有出现(Xcode Swift 4 IOS)
- linux - Linux bash 中的多重重命名
- node.js - 尝试在我的项目文件夹中创建新目录时出错
- html - HTML 和 CSS 模态框的 z-index 问题
- php - 有关于 DataTables 分页类型 =“输入”的问题
- git - 我可以签出 git 上的最新提交吗?
- selenium-webdriver - 类型不匹配:无法从 ChromeDriver 转换为 WebDriver
- angular - 组件文件夹中的角度图像:让编译器将图像移动到资产
- javascript - .each() 不循环所有元素 - jQuery