【问题标题】:Split a string in an array of strings in c在c中的字符串数组中拆分字符串
【发布时间】:2021-10-01 11:35:10
【问题描述】:

我正在尝试根据给定的字符拆分字符串,在本例中为' ',并将每个单词分配给字符串数组并打印出数组的每个元素。

到目前为止,除了最后一个之外,我能够获取字符串的每个单词:(

我如何得到最后一个字?

代码:

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

int main()
{
    char    str[101] = "Hello my name is balou";
    char    temp[101];
    char    arr[10001][101];
    int     count;
    int     i;
    int     j;

    count = 0;
    i = 0;
    j = 0;
    while (str[i] != '\0')
    {
        if (str[i] == ' ' || str[i] == '\n')
        {
            strcpy(arr[count], temp);
            memset(temp, 0, 101);
            count += 1;
            j = 0;
            i++;
        }
        temp[j] = str[i];
        i++;
        j++;

    }

    i = 0;
    while (i < count)
    {
        printf("arr[i]: %s\n", arr[i]);
        i++;
    }
    return (0);
}

输出:

arr[i]: Hello
arr[i]: my
arr[i]: name
arr[i]: is

【问题讨论】:

  • 至于您的问题,您需要在拆分循环后额外调用strcpy 才能获得最后一部分。
  • memset(temp, 0, 101) 也应该在您进入 while 循环之前调用 。顺便说一句,它应该是memset(temp, 0, sizeof(temp)),以防您更改temp 的大小。

标签: arrays c string


【解决方案1】:

既然你这样做了:

while (str[i] != '\0')

你不会做任何最后一句话的strcpy

你可以添加

strcpy(arr[count], temp);
count += 1;

就在while之后

但是……

请注意,您当前的代码存在许多问题。例如双空格、以空格结尾的字符串、以空格开头的字符串等。

继续

char    temp[101];  -->   char    temp[101] = { 0 };

并添加一些代码以确保j 永远不会超过 100

并且...char arr[10001][101]; 的大小可能太大,因为在某些系统上具有自动存储持续时间的变量。

printf("arr[i]: %s\n", arr[i]); --> printf("arr[%d]: %s\n", i, arr[i]);

【讨论】:

  • 太棒了^^谢谢一堆
【解决方案2】:

研究字符串标记strtok函数并访问指针数组所指向的值。
strtok()
array of pointers

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

int main () 
{
  char str[80] = "Hello my name is balou";
  const char s[2] = " "; //delimiter
  char *token; 
  char *words[5]; //store words
  int i = 0;
  
  /* get the first token */
  token = strtok(str, s);
  
  /* walk through other tokens */
  while( token != NULL )
  {
    words[i++] = token;
   
    token = strtok(NULL, s);
  }
  
  int r, c;
  
  // print words
  for (r = 0; r < 5; r++)
  {
    c = 0;
    while(*(words[r] + c) != '\0')
    {
      printf("%c", *(words[r] + c));
      c++;
    }
    printf("\n");
  }
  
  return(0);
}

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    相关资源
    最近更新 更多