Making a string an array

Started by
6 comments, last by DarkNebula 20 years, 5 months ago
How would I create a string array? Like char Moo[5] but have that be an array too? - DarkNebula
Advertisement
char Moo[5] is an array.
Its an array of 5 chars.
If you were to initialize it like this:

char Moo[] = "word"; // you dont need to put the 5 if you init it with a value

then Moo[0] is 'w'
and Moo[3] is 'd'
and Moo[4] is '\n'

[edited by - AndreTheGiant on November 17, 2003 2:12:58 PM]
Uh wait, did you mean having an array of strings? Like having an array, and each value in the array is a separate string? If thats the case, I recommend using vector and string

include <vector>include <string>using std::string;using std::vector<string>;using std::vector<string>::iterator;int main () {  vector<string> myThingy;  myThingy.push_back("hello");  myThingy.push_back("world");  vector<string>::iterator itr;  for (itr = myThingy.begin(); itr != myThingy.end(); itr++) {     cout << (*itr)<<endl;  }  return 0;}




*code not tested, but hopefully close

Edit: without the source tags, angle brackets disappear!

[edited by - AndreTheGiant on November 17, 2003 2:17:42 PM]

[edited by - AndreTheGiant on November 17, 2003 2:18:25 PM]
If you want to use C-style strings (ie - character arrays), then this gets a little tricky. The easiest way would be to create a double array (sometimes called a matrix). Unfortunately every string in the array would have to be the same max length. To get around this you would have to use dynamic memory allocation (which I''m not going to get into). At that point I would recommend that you do what Andre suggested (string and vector). Anyway here is some code:

// this will store 5 strings of 10 characterschar arrayOfStrings[5][10];arrayOfStrings[0] = "badger";arrayOfStrings[1] = "mushroom";arrayOfStrings[2] = "snake";// and so on.
-YoshiXGXCX ''99
Here is the string vector thing from Andre that works:

#include <vector>#include <string>#include <iostream>using namespace std;using std::string;using std::vector<string>;using std::vector<string>::iterator;int main () {  vector<string> myThingy;  myThingy.push_back("hello");  myThingy.push_back("world");  vector<string>::iterator itr;  for (itr = myThingy.begin(); itr != myThingy.end(); itr++) {     cout << (*itr) << endl;  }  return 0;} 


Just fixed it in case someone uses this later.
I just added #include <iostream> and using namespace std; :D Thanks for the input guys.

- DarkNebula

[edited by - DarkNebula on November 17, 2003 2:38:47 PM]
quote:Original post by AndreTheGiant
char Moo[] = "word"; // you dont need to put the 5 if you init
and Moo[4] is ''\n''


Moo[4] is \0 Andre
For constant strings you can do the following:
char *foo[]={"Some string", "some other string", "bar", "whatchu talkin bout willis?"}; 

.
quote:
Moo[4] is \0 Andre


Oops, I knew that!
Im just way more used to typing \n then \0 I guess

This topic is closed to new replies.

Advertisement