0

I'm new to C++ and I've encountered a problem... I can't seem to create an array of characters from a string using a for loop. For example, in JavaScript you would write something like this:

var arr = [];
function setString(s) {
    for(var i = s.length - 1; i >= 0; i--) {
       arr.push(s[i]);
    }
    return arr.join("");
}

setString("Hello World!"); //Returns !dlroW olleH

I know it's a bit complicated, I do have a little bit of background knowledge on how to do it but the syntax of it is still not too familiar to me.

Is there any way that I could do that in c++ using arrays? Could I join the array elements into one string as I do in JavaScript?

It would be greately appreciated if you could help. Thanks in advance. If anyone needs more information just tell me and I'll edit the post.

By the way, my code in c++ is really messy at the moment but I have an idea of what I'm doing... What I've tried is this:

function setString(s) {
    string arr[s.size() - 1];
    for(int i = s.size() - 1; i >= 0; i--) {
        arr[i] = s.at(i); //This is where I get stuck at... 
    //I don't know if I'm doing something wrong or not.
    }
}

It would be nice if someone told me what I'm doing wrong or what I need to put or take out of the code. It's a console application compiled in Code::Blocks

2
  • 2
    Are you doing this as a learning exercise? Because if not, it may be a case of a XY Problem - it is unlikely that it is useful to manually create an array of characters out of a string in this manner. What are you actually trying to do? Commented Oct 25, 2013 at 17:58
  • string arr[s.size() - 1]; ????!!!! Array of strings to store single characters, really? Commented Oct 25, 2013 at 18:07

3 Answers 3

3

std::string has the c_str() method that returns a C style string, which is just an array of characters.

Example:

std::string myString = "Hello, World!";
const char *characters = myString.c_str();
Sign up to request clarification or add additional context in comments.

2 Comments

I think you misread the question (it is rather unclear). Desired output is the string reversed, c_str() is not really related to the problem in any way.
c_str() returns a const char*, not a char*.
1

The closest thing to a direct translation of your function:

string setString(string s) {
    string arr;
    for(int i = s.length() - 1; i >= 0; i--) {
        arr.push_back(s[i]);
    }
    return arr;
}

Comments

1

A std::string is a dynamic array underneath a fairly thin wrapper. There is no need to copy character by character, as it will do it properly for you:

If the character array is null-terminated (that is, the last element is a '\0'):

const char* c = "Hello, world!"; // '\0' is implicit for string literals
std::string s = c; // this will copy the entire string - no need for your loop

If the character array is not null-terminated:

char c[4] = {'a', 'b', 'c', 'd'}; // creates a character array that will not work with cstdlib string functions (e.g. strlen)
std::string s(c, 4); // copies 4 characters from c into s - again, no need for your loop

If you cannot use std::string (e.g. if you are forced to use ANSI C):

const char* c = "Hello, World!";
// assume c2 is already properly allocated to strlen(c) + 1 and initialized to all zeros 
strcpy(c2, c);

In your javascript example, you are reversing the string, which can be done easily enough:

std::string s = "Hello, world!";
std::string s1(s.rbegin(), s.rend());

Additionally, you can cut your iterations in half (for both C++ and Javascript) if you fix your loop (pseudo-code below):

string s = "Hello, world!"
for i = 0 to s.Length / 2
    char t = s[i]
    s[i] = s[s.Length - 1 - t]
    s[s.Length - 1 - i] = t

Which will swap the ends of the string to reverse it. Instead of looping through N items, you loop through a maximum of N / 2 items.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.