info@tutsfinder.in



Strings


Strings are a special case of an array of characters. String is a sequence of characters that are used to store text.

You have already seen some examples of string in the form of string literals that you have been writing into your code:


Std::cout << ”Hello World”;

This is equivalent to using the array declaration:


char TutsFinder = {‘T’,’u’,’t’,’s’,’ ‘,’F’,’i’,’n’,’d’,’e’,’r’,’\0’}; cout << TutsFinder << endl;

Last character in the array is a null character ‘\0’. This is also called the string terminating character because it tells the compiler that the string has ended.

Strings are same as array but there is a difference between them that string is terminated with null character.

Using std::string to initialize, store user input, copy , concatenate and determine the length of the string.



#include <iostream>
#include <string> 
using namespace std;

int main()
{
    string tutsfinder("Hello World");
    cout << tutsfinder << endl;
    
    cout << "Enter String : ";
    string s1;
    getline(cin,s1);
    
    cout << "Enter another String : ";
    string s2;
    getline(cin,s2);
    
    cout << "String after concatenation: ";
    string concat=s1+" "+s2;
    cout << concat << endl;
    
    cout <<"Copied string : ";
    string copy;
    copy=concat;
    cout << copy << endl;
    
    cout << "Length of string : " << concat.length() << endl;
    
}


Output:

Hello World
Enter String : c++
Enter another String : tutorials
String after concatenation: c++ tutorials
Copied string : c++ tutorials
Length of string : 13