首页 > 解决方案 > 单独打印两个绑定在一起的小字符串的最有效方法

问题描述

故事:大弦aaa&bbb是由两个小弦组成的,大弦中两个小弦之间的隔开就是&符号。

任务:使用最有效的方法分别打印第一个和第二个小字符串。

代码 :

char big_str[8] = "aaa&bbb";

期望的输出:

aaa
bbb

标签: c

解决方案


最简单的方法是使用字段宽度'.'修饰符作为"%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

如果您还有其他问题,请告诉我。


推荐阅读