繁体   English   中英

字符串的二维数组

[英]two dimensional array of strings

我尝试制作一个函数来获取像“ 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

有什么想法可以使我更轻松地实现/在哪里改进我的代码?

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

char array[50][200];

然后将一维字符串复制到数组中,您将执行此操作

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字符终止字符串(取决于源字符串的长度),因此需要在复制之后进行。

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

#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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM