C 获取字符串中的第 n 个单词 [英] C get the nth word in a string

查看:66
本文介绍了C 获取字符串中的第 n 个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,它将返回字符数组中的第 n 个单词,例如,如果字符串是:

I am trying to make a function which will return the nth word in char array, for example if the string is:

aaa bbb ccc ddd eee

假设我想获取字符串中的第三个单词,所以它应该返回 ccc.

And lets say that I want to get the third word in the string, so it should return ccc.

这是我目前所拥有的:

#include <stdio.h>
#define SIZE 1000

static char line[SIZE];

int length_to_space(char *s){
    char *i = s;
    while(*i != ' ' && *i != '\0'){
        i++;
    }
    return i - s;
}

char * split_space(char * string, int index){
    char *pointer = string;
    int counted = 0;
    while(*pointer != '\0'){
        if(*pointer == ' '){
            if(counted == index){
                int new_size = length_to_space(++pointer);
                char word[new_size];
                for(int i = 0; i < new_size; i++){
                    word[i] = *(pointer + ++i);
                    return word;
                }
            }
            counted++;
        }
        pointer++;
    }
    return 0;
}

int main(){
    fgets(line, SIZE, stdin);
    char * word = split_space(line, 2);
    printf("%s\n", word);
    return 0;
}

当我运行它并给它一个类似于上面例子中的字符串的字符串时,我得到了一个分段错误.所以我想知道我做错了什么,或者有没有其他方法可以解决这个问题.

When I run this and I give it a string similar to the string in the example above, I get a segmentation fault. So I would like to know what I am doing wrong or is there another approach to the problem.

感谢您的帮助!

推荐答案

char word[new_size]; 创建一个局部变量,该变量在函数返回时被销毁.所以你可以使用 malloc 在堆上动态分配内存

char word[new_size]; creates a local variable which gets destroyed when the function returns. So you can use malloc to dynamically allocate memory on heap


#include <stdio.h>
#include <stdlib.h>
#define SIZE 1000
char line[SIZE];
int length_to_space(char *s) {
  char *i = s;
  while (*i != ' ' && *i != '\0') {
    i++;
  }
  return i - s;
}
char *split_space(int index) {
  char *pointer = line;
  int counted = 1;
  while (*pointer != '\0') {
    if (*pointer == ' ') {
      if (counted == index) {
        int new_size = length_to_space(++pointer);
        char *word = malloc(new_size + 1);// dynamically allocate memory 
        for (int i = 0; i < new_size; i++) {
          word[i] = pointer[i];
        }
        word[new_size] = '\0';// char to end of the string '\0'
        return word;// return should be out of the loop
      }
      counted++;
    }
    pointer++;
  }
  return 0;
}

int main() {
  fgets(line, SIZE, stdin);
  char *word = split_space(2);
  printf("%s\n", word);
  free(word);
  return 0;
}


输入:

aaa bbb ccc ddd eee

输出:

ccc

这篇关于C 获取字符串中的第 n 个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆