String


C++ has two types of representation strings − following

  • The string in the C-style.
  • Introduced with the Standard C++ string class type.

The C-Style Character String

The string C-style originates in C and is still supported in C++. C+ is not supported. In fact, this string is a one-dimensional array of letters that is finished with a null '\0.' A zero-finished string therefore contains the characters of the string which are followed by a zero.

A string consists of the word "Hello" with the accompanying declaration and initialization The character table with the string is one more than the number of characters in the word "Hello" in order to keep the null character at the end of the array.

char greeting[6] = {'H', 'e', 'y', '\0'};

C++ has a large range of null-terminated string handling features.

Sr.No Function & Purpose
1 strcpy(s1, s2);
Copies the string s2 into s1.
2 strcat(s1, s2);
Concatenates the string s2 at the end of s1.
3 strlen(s1);
Returns the string s1’s length.
4 strcmp(s1, s2);
Returns 0 if s1 is same as s2; < 0 if s1 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the character ch’s first occurence in string s1.
6 strstr(s1, s2);
Returns a pointer to the string s2’s first occurrence in s1.

Syntax of strcpy(s1, s2);

strcpy(dest,src);

Example:

#include <iostream> using namespace std; int main () { char str1[]="knowledge2life.com"; char str2[40]; strcpy(str2, str1); cout << "str1: " << str1; cout << "\nstr2: " << str2; return 0; }

OUTPUT:

string type

Syntax strcat()

strcat(str1, str2);

Example:

#include <iostream> using namespace std; int main() { char str1[50] = "knowledge2life"; char str2[50] = ".com"; strcat(str1, str2); cout << str1 ; return 0; }

OUTPUT:

string type

Syntax strlen(s1);

strlen(string_name);

Example:

#include <iostream> using namespace std; int main() { char str1[50] = "knowledge2life.com"; cout << strlen(str1) ; return 0; }

OUTPUT:

string type

Syntax strcmp(s1, s2);

strcmp(string_name, string_name);

Example:

#include <iostream> using namespace std; int main() { char str1[50] = "knowledge2life"; char str2[50] = ".com"; cout << strcmp(str1, str2); ; return 0; }

OUTPUT:

string type

Syntax strchr(s1, ch);

strchr(string_name,finding_char);

Example:

#include <iostream> using namespace std; int main() { char str[] = "knowledge2life.com"; if (strchr(str, 'm') != NULL) cout<< "m is present in knowledge2life.com"; else cout << "m is not present in knowledge2life.com"; }

OUTPUT:

string type

Syntax strstr(s1, s2)

strstr(string, string);

Example:

#include <iostream> using namespace std; int main() { char str1[] = "knowledge2life.com"; char str2[] = "life.com"; cout<< strstr(str1,str2); }

OUTPUT:

string type