给定一个字符串,将其子字符串存储在2D数组中

时间:2014-10-27 03:52:24

标签: c

我被要求编写一个程序,给定字符串“acmprog”,我应该生成并排序一组子串。

所以这是我的代码:

void gen_subStrings(char a[],char sub[][100],int len){
    int i,count=2;
    char first=a[0];
    printf("%c",first);
    for(i=0;i<len-2;i++){
        strncpy(sub[i],a,count);
        printf("%s\n",sub[i]);
        count++;
    }
}

main(){
    char string[]={"acmprog"};

    int len = sizeof(string);
    char subStrings[len][100];

    gen_subStrings(string,subStrings,len);

    system("pause");
}

当我运行它时,输出如下:

 a

应该是:

a
ac
acm
acmp
acmpr
acmpro
acmprog

我做错了什么?

2 个答案:

答案 0 :(得分:0)

每次在字符串结尾处,您都必须复制NULL

 for(i=0;i<len-2;i++)
 {
    strncpy(sub[j],a,count); //Use a different variable
    sub[j][count]='\0';// at end , copy NULL
    printf("%s\n",sub[j++]);
    count++;
 }

答案 1 :(得分:0)

尝试以下

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

#define Literal "acmprog"

void gen_subStrings( const char s[], size_t n, char sub[][n] )
{
    size_t i = 0;
    for ( ; i + 1  < n; i++ )
    {
        strncpy( sub[i], s, i + 1 );
        sub[i][i+1] = '\0';
    }

    sub[i][0] = '\0';
}

int main( void ) 
{
    char string[] = "acmprog";
    size_t n = sizeof( string );

    char subStrings[n][n];

    gen_subStrings( string, n, subStrings );



    for( size_t i = 0; subStrings[i][0] != '\0'; i++ ) 
    {
        printf( "%s\n", subStrings[i] );
    }

    system( "pause" );

    return 0;
}

输出

a
ac
acm
acmp
acmpr
acmpro
acmprog