Strings
Strings
net/publication/348960185
Strings in C++
CITATIONS READS
0 3,719
1 author:
Tarfa Hamed
University of Mosul
38 PUBLICATIONS 283 CITATIONS
SEE PROFILE
All content following this page was uploaded by Tarfa Hamed on 02 February 2021.
1
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq
• To hold the null character at the end of the array, the size of the
character array containing the string is one more than the number
of characters in the word "Hello."
• If you follow the rule of array initialization, then you can write
the above statement as follows:
char greeting[] = "Hello";
• Actually, you do not place the null character at the end of a string
constant.
• The C++ compiler automatically places the '\0' at the end of the
string when it initializes the array. Let us try to print above-
mentioned string:
#include <iostream>
using namespace std;
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
2
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq
strcat(s1, s2);
2.
Concatenates string s2 onto the end of string s1.
strlen(s1);
3.
Returns the length of string s1.
strcmp(s1, s2);
4. Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
strchr(s1, ch);
5.
Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2);
6.
Returns a pointer to the first occurrence of string s2 in string s1.
#include <iostream>
#include <cstring>
using namespace std;
3
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq
int main () {
char str1[10] = "Hello";
char str2[10] = "World";
char str3[10];
int len ;
4
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq
#include <iostream>
#include <string>
using namespace std;
int main () {
return 0;
}
The output of the above program will be the same as the previous
program.
Exercises:
5
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq
Example:
string s1 = “Computer”
If we want to swap the letter ‘r’ in s1 with the letter ‘s’ then the output
should be “Computes”
Example:
string s1 = “Science”;
if we call the above function substr(s1, 2,6), then the output should be
“ience”
6
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq