C + + provides the following two types of string representations:
- C-style string
- String class types introduced by C + +
C-style string
C-style strings originate from the C language and continue to be supported in C + +. The string is actually an array of one-dimensional characters terminated with the null character '% '. Therefore, a null-terminated string that contains the characters that make up the string.
Char greeting[6]={' H ',' E ',' l ',' l ',' O ', ' n '};
Based on the array initialization rules, you can write the above statement as follows:
Char greeting[]="Hello";
The following is a memory representation of a string defined in C/s + +:
In fact, you do not need to put a null character at the end of a string constant. The C + + compiler automatically places ' \ ' at the end of the string when initializing an array.
There are a number of functions in C + + to manipulate null-terminated strings: supports a wide range of functions that manipulate null-terminated strings:
| Serial Number |
Functions & Purposes |
| 1 |
strcpy (s1, S2);
Copy the String s2 to the string S1. |
| 2 |
strcat (s1, S2);
The connection string S2 to the end of the string S1. |
| 3 |
Strlen (S1);
Returns the length of the string S1. |
| 4 |
strcmp (s1, S2);
Returns 0 if S1 and S2 are the same, if S1<s2 returns less than 0 if S1>S2 returns greater than 0. |
| 5 |
STRCHR (s1, ch);
Returns a pointer to the position of the first occurrence of the character ch in the string S1. |
| 6 |
Strstr (s1, S2);
Returns a pointer to the position of the first occurrence of the string S2 in the string s1. |
The String class in C + +
The C + + standard library provides the string class type, supports all of the above operations, and adds additional functionality.
The String class provides a series of operations against strings, such as:
- 1. Append ()--adding characters at the end of a string
- 2. Find ()--Find the string in the string
- 4. Insert ()--insertion character
- 5. Length ()--Returns the lengths of the strings
- 6. Replace ()--replace string
- 7. substr ()--Return a substring
C + + string