A
A
Alexander2018-09-12 16:35:49
C++ / C#
Alexander, 2018-09-12 16:35:49

How to correctly split a string by spaces and add it to an array?

You need to split the input string by spaces and put the resulting substrings into an array.
I did it like this:

  1. Create a dynamic array of strings consisting of two el-s
  2. In the loop, go through the characters of the input string, if there is a space, then add this word to the array
  3. Create a temporary dynamic array to increase the size of the main
  4. Output the resulting substrings and remove the array
My code
#include "stdafx.h"
#include <iostream>

using namespace std;

int main() {
  char input[] = "Hello world! I am Alex! I'm from Russia\0";
  char *p = input;

  int index = 2;
  char **arr = new char*[index];
  int n = 0, m = 0;  // Индексы для управления массивом
                    // n - индекс подстроки в массиве
                   // m - индекс символа в подстроке

  while (*p) {
    if (*p != ' ' && *p) {
      arr[n][m] = *p;
      m++;
    }
    else {
      arr[n][m] = '\0';
      m = 0;

     // Увеличение массива
      char **temp = new char*[index];
      for (int i = 0; i < index; i++) {
        temp[i] = arr[i];
      }
      arr = new char*[index++];
      for (int i = 0; i < index-1; i++) {
        arr[i] = temp[i];
      }

      delete[] temp;
    }
    p++;

 // Вывод подстрок
  for (int i = 0; i < index; i++)
  {
    cout << arr[i] << endl;
  }

  delete[] arr;

  return 0;
}


But this code has an error:
Screenshot with error
5b9915f007d80943197993.png
PS I will be glad if you offer a shorter version

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Makarov, 2018-09-12
@AlexNineteen

Well, if you’re right on the space, and if it’s really in C ++, then here:

#include <iostream>
#include <sstream>
#include <vector>

int main()
{
  std::istringstream input{ "foo bar baz qux" };
  std::vector<std::string> result;

  // extract substrings one-by-one
  while (!input.eof()) {
    std::string substring;
    input >> substring;
    result.push_back(substring);
  }

  // print all the extracted substrings
  for (const std::string& substring : result) {
    std::cout << substring << std::endl;
  }
}

In general , there are so many options here that it’s impossible to count (there is even a shorter version using std::copy).

V
Vitaly, 2018-09-13
@vt4a2h

I implemented my own version not so long ago: https://github.com/vt4a2h/str_utils
Well, there are a lot of options on the Internet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question