|
|
|
Strings in C++
Strings are a row of characters that ends with the null-character (\0). This is called a null-terminated string.
You can store a string in a character-array.
Example :
char s[15] = "Charlotte";
| array s |
'C' |
'h' |
'a' |
'r' |
'l' |
'o' |
't' |
't' |
'e' |
'\0' |
|
|
|
|
|
| index |
0 |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
There are 15 position reserved for the string s. (0-14). The name Charlotte is only 9 positions long and the null-character is added automatically. The last 5 positionsin the array are not used.
Remember, in a array of 15 character you can maximal put a string of 15 characters, cause the null-character uses 1 position.
Entering a string from keyboard
#include <iostream.h>
void main()
{
char s[15];
cout << "Enter a string" << endl;
cin >> s;
cin.get();
cout << "The entered string is: " << s;
cin.get();
}
There are 2 problems with this code :
- It would be easy to enter a string lager then 14 characters. (In c++ there is no boundary check).
- You can only enter 1 word. When you enter a space, cin thinks you are finished.
Better code:
#include <iostream.h>
void main()
{
const int number=15;
char s[number];
cout << "Enter a string" << endl;
cin.get(s,number);
cout << "The entered string is: " << s;
cin.get();
}
Another function you can use to read characters in is cin.getline().
char buffer[80];
cin.getline(buffer,80);
Functions for strings
To use these functions you need to include <string.h>
- strlen()
Gives you the length of the string. length=strlen(str);
size_t strlen(const char * str);
- strcpy() and strncpy()
Copies 1 string to another string. strcpy(dest,src);.
strncpy is the same but you can add max size to copy. strncpy(dest,src,10);.
char * strcpy(char * dest,const char * src);
- strcat()
With this you place string2 to the end of string1.
char * strcat(char * dest, const char * src);
- strcmp()
This function compares 2 strings, and makes difference between small and large letters.
int strcmp(const char * s1,const char * s2);.
If the function returns 0 the strings are the same. If it returns a number smaller as 0 then s1 comes before s2, alphabetically s1 comes before s2.
- strcmpi() or stricmp()
Same as strcmp() but makes no difference between small and large letters. (i stands for ignore).
int stricmp(const char * s1,const char * s2);
- strncmp()
This function compares max number of characters from s1 with s2, and makes difference between small and large characters.
int stricmp(const char * s1,const char * s2, size_t maxlen); (size_t is another name for unsigned int).
- strnicmp()
Same as strcmp() but make no difference between small and large characters.
int strnicmp(const char * s1,const char * s2, size_t maxlen);
TOP
|
|