Count the height and width of an "image" (char * using \ n) - C ++

2

Good evening! In one of the parameters of my constructor, I'm passing the following char *

+---+\n|A  |\n| H |\n|  A|\n+---+

Next, the constructor calls SetText (), passing this char *, and within SetText (), I would have to count the height and width of this "image", which would be 5x5. I assume it's using \ n .

I've been looking for various functions or algorithms to split \ n, but not one successfully.

In PHP, there is the split () that distributes the string in the desired char and separates everything else into arrays (which would already tell the height and width), there is something similar / equal in C ++?

Thank you.

    
asked by anonymous 01.12.2015 / 01:16

1 answer

1

Suggest the use of std::string instead of char * , whenever possible.

You can create your own generic function to separate a std::string of data from a delimiter.

Here is an example using only std library functions.

#include<string>
#include<sstream>
#include<vector>
#include<iterator>

using namespace std;

vector<string> *splitHelper(const string &str, char delimiter, vector<string> &elements) {
    stringstream ss(str);
    string item;
    while (getline, item, delimiter)) {
      elements.push_back(item);
    }
}

vector<string> splitString(const string &str, char delimiter) {
    vector<string> elements;
    splitHelper(str, delimiter, elements);
    return elements;
}

int main(int argc, char* argv[]) {

    char *test = "+---+\n|A  |\n| H |\n|  A|\n+---+";  //este passo é desnecessário. Uma vez que estás a usar C++ deverias usar, sempre que possível, 'std::string' ao invés de usar 'char *'

    string str(test);
    const vector<string> words = splitString(str, '\n');

    //imprimir as palavras
    copy(words.begin(), words.end(), ostream_iterator<string>(cout, "\n");
}

The words will contain each of the elements. You can determine the size of the image by counting the number of characters of each of the elements. The height of the image will be the total number of elements of the words vector.

    
01.12.2015 / 11:10