string s = "hello";
cout << s[0] << endl;
cout << s[4] << endl;
s[0] = 'x';
cout << s << endl;
The above code will print out the following (drag your mouse for the answer):
h
o
xello
string is not an arraystring is not a basic built-in type in C++. It
is a type that is defined in the string library, as we will
eventually learn to define new types in our programs.
| string | array |
|
You can simply declare a string:
As in the above, if you don't initialize s with any specific
string, s is ensured to be a string with length 0 (an empty
string).
You can change its contents (even its length) freely.
|
You need to use new to create an array:
You can change its contents, but unfortunately, you cannot change its size:
If you really want to change both the contents and size of an array, you need
to destroy it and create a new one:
|
| string | array |
It's easy with strings: Put a .length() at the end of it and the
resulting expression returns the length of the string. For example:
The code will print 5. |
Built-in arrays don't provide a .length() function. For an array,
it is you who should store its size in an int variable like
n. Then, you can refer to n if you want to know the
size of an array later. |
lastname, firstnameIn addition, all the letters should be capitalized.
int main()
{
string first, last;
// read
cin >> first >> last;
// write: we will create a function capitalize() that capitalizes a string
cout << capitalize(last) << ", " << capitalize(first) << endl;
}
In the above, we assumed that we have a function string
capitalize(string) that capitalizes a string. Now, it is time to
write it!
// prototype -- it should be placed before main()
string capitalize(string w);
// definition
string capitalize(string w) // NOTE: remember the principle of pass by value
{
// empty string s
string s;
for(int i = 0; i < w.length(); i++) // NOTE: .length() was used
{
char c = w[i]; // NOTE: type of w[i] is char
// if c is a lowercase letter, capitalize it
if( 'a' <= c && c <= 'z')
c = 'A' + (c - 'a');
// add c to s
s += c;
}
return s;
}
string capitalize(string w)
{
for(int i = 0; i < w.length(); i++)
{
// if w[i] is a lowercae letter
if( 'a' <= w[i] && w[i] <= 'z')
w[i] += 'A' - 'a'; // capitalize w[i]
}
return w;
}
string* p = new string[3]; // p: string*
p[0] = "hello";
p[1] = "world";
p[2] = "array of strings";
cout << p[2] << endl; // p[2]: string
cout << p[2][4] << endl; // p[2][4]: char
delete [] p;
The code will print out the following (drag your mouse for the answer):
array of strings
y
string
s and a
char c, and tests whether or not c
appears in s.