Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String questions 1

Status
Not open for further replies.

fugigoose

Programmer
Jun 20, 2001
241
US
If i include <string> and do the 'using namespace std' thing, to declare a string can i simply do this?

string myString;

int main(){
myString = &quot;Duck&quot;;
myString = &quot;Goose&quot;;
}

Does that code look leagal? Also, is there a way to retrieve one char of a string? I dont know if this would work...

myChar = myString[3];

Are strings good to use, or would a vector of chars be better for text manipulation.

Thanks
 
Your code is legal. You can make a string by declaring it just like you would an int:
Code:
#include <iostream>
#include <string>
using namespace std;

int main()
{
    int j;
    j = 3;
    string myString;
    myString = &quot;Duck.&quot;;
    int k = 4;
    string yourString = &quot;goose&quot;;
    yourString += &quot; and grimm&quot;;
    char g = yourString[0];
    int yourLength = yourString.length();
    for (int i = 0; i < yourLength; i++)
    {
        cout << &quot;Char #&quot; << i << &quot;: &quot; << yourString[i] << endl;
    }
    cout << &quot;The whole string is: &quot; << yourString << endl;
}
And yes, strings are definitely good to use. There are some occasions where a vector of chars might be more appropriate, but for basic string usage the standard string is the way to go. There are lots of member functions available like find_first_of that might be helpful text manipulation and that aren't as easy to do with a vector of chars.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top