最有效的方法来分别打印2个绑定在一起的小字符串

问题描述 投票:0回答:1

故事:aaa&bbb的大字符串由两个小字符串组成,将大字符串中的两个小字符串分开的是&符号。

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

代码:

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

所需的输出:

aaa
bbb
c
1个回答
0
投票

[最简单的方法就是对'.'中的"%s"格式说明符和例如两个指针使用field-widthprintf修饰符>

#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

让我知道是否还有其他问题。

© www.soinside.com 2019 - 2024. All rights reserved.