简体   繁体   English

拆分字符串数组中的字符串 c

[英]Split a string in an array of strings in c

I am trying to split a string based on a given char, in this case ' ' and assign each word to an array of strings and print out each element of the array.我试图根据给定的字符拆分字符串,在本例中为' ' ,并将每个单词分配给字符串数组并打印出数组的每个元素。

So far, I am able to get each word of the string except for the last one:(到目前为止,我能够得到字符串的每个单词,除了最后一个:(

How do I get the last word?我如何获得最后一句话?

code:代码:

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

output: output:

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

Since you do:因为你这样做:

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

you won't do any strcpy of the last word.你不会做最后一个词的任何strcpy

You can add你可以加

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

just after the while过了一会while

But...但...

Notice that your current code has a number of problems.请注意,您当前的代码存在许多问题。 For instance double spaces, strings ending with a space, strings starting with a space, etc.例如双空格、以空格结尾的字符串、以空格开头的字符串等。

Further do进一步做

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

and also add some code to ensure that j never exceeds 100并添加一些代码以确保j永远不会超过 100

and... the size of char arr[10001][101];和... char arr[10001][101]; may be too big as a variable with automatic storage duration on some systems.在某些系统上,作为具有自动存储持续时间的变量可能太大。

And

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

Research string token strtok function and accessing values pointed by array of pointers.研究字符串标记strtok function 并访问指针数组指向的值。
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);
}

OUTPUT: OUTPUT:
在此处输入图像描述

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

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