Strings

String is a sequence of characters terminated with a null character \0 at the end. There are two types of strings in C++.

  1. C-Strings
  2. Strings that are objects of string class

How to declare strings

Declaring strings is similar to one-dimensional character array. Below is the syntax:


How to initialize strings

Strings can be initialized in a number of ways:


How to read strings from console


Check Result here

Consider if you have given One Compiler as input in the stdin. Surprisingly you get One alone as output. That is because a white space is present between One and Compiler. So how can you read a entire line which also has white spaces in it.

Consider your input string is Hello Everyone.. Happy Learning!!


Check Result here

String Functions

C++ has various in-built string functions which can manipulate null-terminated strings.

Function nameDescription
strlen(str)to return the length of string str
strcat(str1, str2)to concatenate string str2 onto the end of string str1.
strcpy(str1, str2)To copy string str2 into string str1.
strcmp(str1, str2)returns 0 if str1 and str2 are the same and less than 0 if str1 < str2 and a positive number if str1 > str2
strchr(str, c)Returns a pointer to the first occurrence of character c in string str
strstr(str1, str2)Returns a pointer to the first occurrence of string str2 in string str1

Examples


Check result here