【问题标题】:C program to extract different substrings from array of stringsC程序从字符串数组中提取不同的子字符串
【发布时间】:2014-10-15 09:15:28
【问题描述】:

我想从包含字符串数组的文件中提取不同的子字符串。我的文件与此类似。

abcdxxx
efghijkyyy
lmzzz
ncdslanclsppp
kdfmsqqq
cbskdnsrrr 

我想从上面的文件中提取 xxx、yyy、zzz、ppp、qqq、rrr(基本上是最后 3 个字符)并存储到一个数组中。我引用了这个链接How to extract a substring from a string in C?,但觉得不可行,因为我文件中的内容是动态的,可能会在下次执行时发生变化。有人可以简要介绍一下吗? 这是我的方法

     FILE* fp1 = fopen("test.txt","r");
     if(fp1 == NULL)
     {
        printf("Failed to open file\n");
        return 1;
     }
     char array[100];
     while(fscanf(fp1,"%[^\n]",array)!=NULL);

     for(i=1;i<=6;i++)
     {
        array[i] += 4;
     }

【问题讨论】:

  • 您的“方法”看起来像存根代码。到目前为止,您是否尝试过其他方法?

标签: c arrays string file


【解决方案1】:

我的文件中的内容是动态的,下次执行时可能会发生变化

那你需要realloc或者链表:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    FILE *f;
    char **arr = NULL;
    char s[100];
    size_t i, n = 0;

    f = fopen("text.txt", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while (fgets(s, sizeof s, f) != NULL) {
        arr = realloc(arr, sizeof(*arr) * (n + 1));
        arr[n] = calloc(4, 1);
        memcpy(arr[n++], s + strlen(s) - 4, 3);
    }
    fclose(f);
    for (i = 0; i < n; i++) {
        printf("%s\n", arr[i]);
        free(arr[i]);
    }
    free(arr);
    return 0;
}

输出:

xxx
yyy
zzz
ppp
qqq
rrr

如果您总是想要最后 3 个字符,您可以简化:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    FILE *f;
    char (*arr)[4] = NULL;
    char s[100];
    size_t i, n = 0;

    f = fopen("text.txt", "r");
    if (f == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    while (fgets(s, sizeof s, f) != NULL) {
        arr = realloc(arr, sizeof(*arr) * (n + 1));
        memcpy(arr[n], s + strlen(s) - 4, 3);
        arr[n++][3] = '\0';
    }
    fclose(f);
    for (i = 0; i < n; i++) {
        printf("%s\n", arr[i]);
    }
    free(arr);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-09-29
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多