Strings in C++

Introduction to strings

  • Strings are objects that represent sequence of characters.
  • Strings are the array of characters that is char data type.
  • It terminates with NULL character (ASCII value is 0) that is '\0' to indicate the termination.
  • Example:
    char str[] = "ABC";
  • In the above example, str is a string and holds 4 characters. Originally it has 3 characters that is "ABC", but the NULL character '\0' is added to the end of the string automatically.
  • If a string "ABC" is stored into an array, it will consume 6 spaces or memory bytes.
This string will be stored as follows:

str[0]'A'
str[1]'B'
str[2]'C'
str[3]'\0'

There are three ways of defining the string:

i. char str[4] = “ABC”;
ii. char str[] = {'A', 'B', 'C', '\0'};
iii. char str[4] = {'A', 'B', 'C', '\0'};

String Functions

String FunctionsDescription
strcpy()It copies string from one string to another string.
strcat()It combines two strings(concatenation) to linked together.
strlen()It returns the length of the string.
strcmp()It compares the two strings.
strchr()It returns the pointer of character.
strstr()It returns the pointer of string.

Example : Demonstrating the string operation

Displays the length of the string and concatenate string without using string function.

#include <iostream>
#include <string>
using namespace std;     //we can also used std::string instead of std.
int main ()
{
     string str1 = "Welcome to ";
     string str2 = "TutorialRide";
     string str3;
     int  len ;
     str3 = str1 + str2; //Concatenates str1 and str2
     cout<<"Concatenate String : "<<str3<< endl;
     len = str3.size();  //Total length of str3 after concatenation
     cout << "String Length is : " << len << endl;
     return 0;
}


Output:
Concatenate String : Welcome to TutorialRide
String Length is : 23

Passing String to a Function

Strings are passed to a function in the same way as arrays are passed to a function.

Example : Demonstrating the passing string to a function

#include <iostream>
using namespace std;
void display(char s[]);
int main()
{
    char str[25]="Welcome to TutorialRide";
    display(str);
    return 0;
}
void display(char s[])
{
    cout<<s;
}


Output:
Welcome to TutorialRide