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

Asked

Viewed 114 times

2

Good evening! In one of the parameters of my builder, I am passing the following char *

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

Then the constructor calls Settext(), passing that char*, and inside Settext(), I would have to count the height and width of this "image", which would be 5x5. I assume it’s using the \n.

I’ve been looking for several functions or algorithms to split the n, but not one successfully.

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

Thank you.

1 answer

1


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

You can create your own generic function to separate a std::string of data 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 vector 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 vector elements words.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.