user997112
user997112

Reputation: 30605

C++ creating a string from char array elements?

I have a char array which is VERY large and I iterate through the array. I look for patterns with logic such as:

if (array[n] == 'x' and array[n+1] == 'y' and array[n+2] == 'z')
{
    mystring = array[n+4] + array[n+5];
}

if array[n+4] is '4' and array[n+5] is '5' then mystring = "45"

However, mystring is always "", what am I doing wrong? I don't want to use substring as the array is too large. I just want to cast the chars to strings and then append to mystring.

Upvotes: 1

Views: 3816

Answers (5)

ilmale
ilmale

Reputation: 406

I suggest so use assign(const char*, len); no copy constructor is involved

if (array[n] == 'x' and array[n+1] == 'y' and array[n+2] == 'z')
{
   mystring.assign(array + n + 4, 2);
}

Upvotes: 4

Renan Gemignani
Renan Gemignani

Reputation: 2793

Adding characters strings doesn't work like that in C++. The easier way to do this is to create a stringstream and add the characters to the string with the << operator, then recover a string from it using the str() method.

Example:

#include <iostream>
#include <sstream>

using namespace std;

int main(void)
{
    char a[] = {'a', 'd', 'c', 'b', 'a' };
    stringstream linestream;
    linestream << a[0] << a[1];
    cout << linestream.str() << endl; // Prints ad
    return 0;
}

Upvotes: 0

Vivian Miranda
Vivian Miranda

Reputation: 2485

If you can't use std::string in the first place, as suggested by @P0W (which is a good suggestion), then there is another alternative to do this conversion that does not involve string constructor (I think the solution using string constructor is a great one, but knowing different approaches can give you more flexibility), but relies on std::string::append.

int main ()
{
    // create char
    char *str1 = new char[6];
    strcpy( str1,"hello ");
    char *str2 = new char[5];
    strcpy(str2, "world" );

    // use of append to convert to a string
    std::string mystring;
    mystring.append(str1);
    mystring.append(str2);
    std::cout << mystring << std::endl;
}

Check the std::string::append documentation, and you will also see that one of the overloading of this functions is string& append (const char* s, size_t n), which means you can convert just subset of char arrays, as you request it.

Upvotes: 0

P0W
P0W

Reputation: 47784

You're checking for a consecutive "xyz" occurrence , why not simply use std::string ?

std::string s(array);

size_t i =s.find("xyz");
if(i!=std::string::npos && i+5 <= s.size())
{
    std::string mystring = std::string(1,array[i + 4]) + array[i + 5];
    std::cout<<mystring;
}

Upvotes: 2

Jonathan Marshall
Jonathan Marshall

Reputation: 121

You can cast chars to ints and vice versa because they are basic language types. Strings are implemented as a class so you need to invoke the string constructor for both chars then concatenation the two resulting strings into mystring

Upvotes: 0

Related Questions