-1

I'm working on a console in C and I want to make some commands. I simply take user input with getline(), and then I have a string of characters. The problem is that I want to split the string into smaller "words", and the seperator would be the whitespace character (" ").

For example, the string of characters "Hello World!" would be split into {"Hello", "World!"}, so I want to ignore invisible characters like whitespaces, \n, \t and other invisible characters.

Basically, I want something like the string.split() function in Python. The function would return a array with all the strings ({{'H', 'e', 'l', 'l', 'o', '\0'}, {'W', 'o', 'r', 'l', 'd', '!', '\0'}}) .

I'm fairly new to C, but I do have some experience in C++.

I tried finding some builtin functions, but considering it is C, not C++, I could not find anything appropriate for my problem. I still do not really understand how do arrays work in C.

  • 2
    Great! So do that - split the string. So what exactly are you struggling with? Find the space, replace it with zero, realloc an array, fill with the pointer to string, return. You might also be interested in strtok() – KamilCuk Aug 15 '23 at 11:24
  • I'm struggling with actually making the function and allocating and reallocating, I don't have any experience with allocating. I heard about strtok(), but I'd like to have a little function from which I can learn. I want to see how it would work, so I can possibly use that knowledge in the future. – matthewihweroush Aug 15 '23 at 11:30
  • 2
    `struggling with actually making the function` Take a [good C book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) and classes. What research did you do? C is 50 years old, there are millions of examples with "string split on spaces" functionality. https://www.google.com/search?q=C+split+string+by+spaces https://stackoverflow.com/questions/4513316/split-string-in-c-every-white-space – KamilCuk Aug 15 '23 at 11:52

0 Answers0