二维字符串数组

时间:2015-01-21 22:08:22

标签: c arrays string

我尝试创建一个函数来获取像“Hello”这样的字符串。 函数的返回值应该是一个看起来像

的字符串数组
H
He
Hel
Hell
Hello

我真的不知道该怎么做。我现在的代码非常混乱,因为我做了很多调整,每个人都让它变得更糟。

char stutterString(char string[])
{
  rowLength = strlen(string);
  char help_string[][rowLength]; // I wanted to make the onedimensiol string i get into a two dimensial one so I can then compare my strings in a forloop 

    strcpy(help_strig, string); // I'm not sure if that's how you copy a 1d string into a 2d string, I guess not.

我的循环看起来像

for(; count1 <= COLUMN; count1++)
  {
    for(count2 = 0; count2 <= NumberRow; count2++)
    {
      new_string[count1][ROW] = help_string[0][count2];

      ROW++
    }
    NumberRow++;
  }

// NumberRow indicates the limit on the letters that should be copied. like in the beginning it's 1 for H, then 2 for the He and so on..
//count1 is for the column number we r currently and count2 for the row

我有什么想法可以更容易地实现我的代码?

2 个答案:

答案 0 :(得分:1)

您需要声明一个二维数组,例如

char array[50][200];

然后将1D字符串复制到数组中,您可以执行此操作

strcpy( array[0], "Hello" );

要将字符串的一部分从2D数组复制到另一个2D数组,请使用strncpy函数,例如

length = 3;
strncpy( new_string[index], help_string[10], length );
new_string[index][length] = '\0';

这会将help_string[10]的前3个字符复制到new_string数组中。请注意strncpy可能不会终止带有NUL字符的字符串(取决于源字符串的长度),因此需要在复制后完成。

答案 1 :(得分:0)

这应该为你做。使用动态分配可以减少程序在运行时的内存占用量以及可执行文件的文件大小。

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

char **
stutterString(char *str)
{
  int i, sz, len=strlen(str);
  char **rtn; /* a 2-dimensional array */
  char *s;

  /* allocate the number of rows plus an extra one to indicate the end of list.
     calloc() will set all "rows" to NULL.
  */
  rtn = (char **)calloc(len+1, sizeof(char **));
  for(i=0; i<len; ++i) {
    /* allocate the string -
      '2' is 0 offset plus i plus 1 for \0
    */
    s = (char *)malloc(sizeof(char *) * (i+2));
    memcpy(s, str, i+1);
    s[i+1] = '\0';
    rtn[i] = s;
  }

  return(rtn);
}

int
main()
{
  int i;
  char **stutter;   /* think of it as a 2-dimensional array */

  stutter = stutterString("hello");

  /* Print and free the string. It's important to free when
     you are done with the memory! */
  for(i=0; stutter[i]!=NULL; ++i) {
    puts(stutter[i]);
    free(stutter[i]);
  }
  free(stutter); /* free the array itself */

  return(0);
}