简体   繁体   English

将字符串拆分为字符串数组

[英]Splitting a string to an array of strings

I'm trying to split a sentence the user inputs to an array of words so I can later manipulate the words separately as strings.我正在尝试将用户输入的句子拆分为一组单词,以便稍后我可以将这些单词分别作为字符串进行操作。 The code is compiling but prints only garbage after the user input.代码正在编译,但在用户输入后只打印垃圾。 I tried debugging but don't see the problem.我试过调试,但没有看到问题。 Can someone help me fix it?有人可以帮我解决吗?

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

int main() {
    char str[1000];
    int i = 0;
    char rev[1000][1000];
    int r = 0;

    puts("Enter text:");

    gets(str);

    int k, length = 0;
    printf_s("So the words are:\n");
    while (str[i] != '\0') {
        if (str[i] == ' ') {
            k = i - length;

            do {
                rev[r][k] = (str[k]);
                k++;
            } while (str[k] != ' ');
            printf(" ");
            length = (-1);
            r++;
        } else
        if (str[i + 1] == '\0') {
            k = i - length;

            do {
                rev[r][k] = (str[k]);
                k++;
            } while (str[k] != '\0');
            length = 0;
            r++;
        }

        length++;
        i++;
    }
    for (int r = 0; r < 1000; r++) 
        printf("%s ", rev[r]);

    return 0;
}

If you wish to split a string into an array of strings, you should consider the strtok function from #include <string.h> .如果您希望将一个字符串拆分为一个字符串数组,您应该考虑使用#include <string.h>strtok函数。 The strtok function will the split the string on the given delimiter(s). strtok函数将在给定的分隔符上拆分字符串。 For your case, it would the " " .对于您的情况,它将是" "

Using the strtok example from Tutorials Point:使用 Tutorials Point 中的strtok示例:

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

int main(){
   char str[80] = "This is - www.tutorialspoint.com - website";//The string you wish to split
   const char s[] = "-";//The thing you want it to split from. But there is no need to this.
   char *token;//Storing the string
   
   /* get the first token */
   token = strtok(str, s);//Split str one time using the delimiter s
   
   /* walk through other tokens */
   while( token != NULL ) 
   {
      printf( " %s\n", token );//Print the string
    
      token = strtok(NULL, s);//Split the string again using the delimiter
   }
   
   return(0);
}

Replace you declaration替换你的声明

char rev[1000][1000];

with

char * rev[1000];                  // We will need pointers only
int    i = 0;                      // Index to previous array

and all your code after以及之后的所有代码

    puts( "Enter text:" );

with this:有了这个:

    fgets( str, 998, stdin );      // Safe way; don't use gets(str)

    const char delim[] = ",; ";    // Possible delimiters - comma, semicolon, space
    char *word;

    /* Get the first word */
    word     = strtok( str, delim );
    rev[i++] = word; 

    /* Get the next words */
    while( word != NULL ) 
    {
       word     = strtok( NULL, delim );
       rev[i++] = word;
    }

    /* Testing */
    for (int r = 0; r < i - 1; r++) 
        printf( "%s\n", rev[r] );

    return 0
}

As you can see, all dirty work is done with the strtok() function ("string to tokens") which walks through other and other words ("tokens") , recognizing them as delimited by one or more characters from the string delim .如您所见,所有脏活都是使用strtok()函数(“string to tokens”)完成的,该函数遍历其他和其他单词(“tokens”) ,将它们识别为由字符串delim一个或多个字符分隔。


fix like this像这样修复

#include <stdio.h> 

int main(void) {
    char str[1000];
    char rev[1000][1000];

    puts("Enter text:");
    fgets(str, sizeof str, stdin);//Use fgets instead of gets. It has already been abolished.

    int r = 0;
    int k = 0;

    for(int i = 0; str[i] != '\0'; ++i){
        if (str[i] == ' ' || str[i] == '\n'){//is delimiter
            if(k != 0){
                rev[r++][k] = '\0';//add null-terminator and increment rows
                k = 0;//reset store position
            }
        } else {
            rev[r][k++] = str[i];
        }
    }
    if(k != 0)//Lastly there was no delimiter
        rev[r++][k] = '\0';

    puts("So the words are:");
    for (int i = 0; i < r; i++){
        printf("%s", rev[i]);
        if(i < r - 2)
            printf(", ");
        else if(i == r - 2)
            printf(" and ");
    }

    return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int count_spaces(char *str)
{
  if (str == NULL || strlen(str) <= 0)
    return (0);

  int i = 0, count = 0;
  while (str[i])
    {
      if (str[i] == ' ')
    count++;
      i++;
    }

  return (count);
}

int count_char_from_pos(char *str, int pos)
{
  if (str == NULL || strlen(str) <= 0)
    return 0;

  int i = pos, count = 0;
  while (str[i] && str[i] != ' ')
    {
      count++;
      i++;
    }

  return count;
}

char **get_words(char *str)
{
  if (str == NULL || strlen(str) <= 0)
    {
      printf("Bad string inputed");
      return NULL;
    }

  int i = 0, j = 0, k = 0;
  char **dest;

    if ((dest = malloc(sizeof(char*) * (count_spaces(str) + 1))) == NULL
    || (dest[0] = malloc(sizeof(char) * (count_char_from_pos(str, 0) + 1))) == NULL)
      {
    printf("Malloc failed\n");
    return NULL;
      }

  while (str[i])
    {
      if (str[i] == ' ') {
    dest[j++][k] = '\0';
      if ((dest[j] = malloc(sizeof(char) * (count_char_from_pos(str, i) + 1))) == NULL)
        {
          printf("Malloc failed\n");
          return NULL;
        }
      k = 0;
    }
      else { 
      dest[j][k++] = str[i];
    }

      i++;
    }

  dest[j][k] = 0;
  dest[j + 1] = NULL;
  return dest;
}

int main(void) {
    char *line = NULL;
    size_t n = 0;
    getline(&line, &n, stdin);
    printf("%s\n", line);
    line[strlen(line) - 1] = 0;
    printf("%s\n", line);

    char **tab = get_words(line);

    int i = 0;
    while (tab[i])
      {
    printf("%s\n", tab[i++]);
      }
}

here is a long but fully working example get the user input then send it to get_words function.这是一个很长但完全有效的示例,获取用户输入然后将其发送到 get_words 函数。 It will get the number of words, the number of characters for each words, allocate everything in memory and writes chars then return it.它将获取单词数,每个单词的字符数,分配内存中的所有内容并写入字符然后返回它。 You get a char ** and prints it just tested it it works你得到一个字符 ** 并打印它只是测试它它的工作原理

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

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