Strings in C++
- One dimensional arrays is used to create character strings
- In C++, a string is defined as a character array that is terminated by a null
- A null is specified using ‘\0’
- Because of the null terminator, it is necessary to declare a string to be one character longer
Arrays of characters
All strings end with null (‘\0’)
Examples
- char string1[] = “hello”;
- Null character implicitly added
- string1 has 6 elements
- char string1[] = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’ };
Subscripting is the same
- string1[ 0 ] is ‘h‘
- string1[ 2 ] is ‘l’
Reading strings from keyboard
- The easiest way to read a string entered from the keyboard is to make a character array
int main()
{
char str[80];
cout << “Enter a string: “;
cin >> str; // read string from keyboard
cout << “Here is your string: “;
cout << str<<“\n”;
return 0;
}
String
Input from keyboard
char string2[ 10 ];
cin >> string2;
Puts user input in string
- Stops at first whitespace character
- Adds null character
If too much text entered, data written beyond array
Printing strings
cout << string2 << endl;
- Does not work for other array types
Characters printed until null found
Reading strings from keyboard
There is a problem with previous program, if the string has whitespace characters
// Using gets() to read a string from the keyboard.
int main()
{
char str[80];
cout << “Enter a string: “;
gets(str); // read a string from the keyboard
cout << “Here is your string: “;
cout << str<<“\n”;
return 0;
}
- Remember neither cin nor gets() performs any bounds checking on the array
#include <iostream.h>
int main()
{
char string1[ 20 ], string2[] = “string literal”;
cout << “Enter a string: “;
cin >> string1;
cout << “string1 is: ” << string1
<< “\nstring2 is: ” << string2;
return 0;
}
String Functions
We can implement many functions using strings:
- String copy
- String length
- String compare
- String Concatenate
- To Upper (char(string1[ i ] -32))
- To Lower
- Is Alphabetical
- Is Digit
String concatenate
bool stringcopy (char str1[], char str2[], char str3[])
{
int i=0,j=0;
while (str1[i]!=’\0′) // loop to copy string 1 in string 3
{
str3[i]=str1[i];
i++;
}
str3[i++]=’ ‘; // add a space between two strings and increment the counter
while (str2[j]!=’\0′) // loop to copy string 2 in string 3
{
str3[i]=str2[j];
i++;
j++;
}
str3[i]=’\0′;//add the termination character in merged string
if (i==1)// if both strings are empty, the only character in the merged string in the SPACE
return false; // use of bool return type
else
return true;
}
void main ()
{
char string1[ 20 ]=”string 1″, string2[] = “string2 literal”, str3[40];
if (stringcopy(string1, string2,str3))
cout << “string3 is: ” << str3<<endl;
else
cout<<“strings are empty!”<<endl;
}