• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C++ » String in C++
Next →
← Prev

String in C++

By Dinesh Thakur

Just like a group of integers can be stored in an integer array. Similarly, a group of characters can also be stored in a character array. This array of characters is known as a string. Strings are used for storing and manipulating text such as words and sentences.

A string in C++ is a collection of characters terminated by a null character (‘\0’), specifying where the string terminates in memory. A string can be represented as a one-dimensional char type array where each string’s character is stored as an element of the array. For example: “Try Again” is a string constant stored in memory, as shown below figure.

Each element of the string is stored in a contiguous memory location and terminated by a null character (‘\0’) which is automatically inserted by the compiler to indicate the string’s end.

A string constant is always enclosed in double quotes (” “) and may include alphabets, numbers, escape sequence, blank space and special characters etc. Some of the valid string constants are “Good morning” , “27”, ” “, “41-B”, “121+31-43” and “B”.

Strings representation in memoryDefining and Initializing String Variables

The strings are an array of characters, so they are defined as

char array_name[size];

where array_name is the name of the string, and size represents the maximum number of characters that can be stored, and it must be a positive integer value. Consider an example

char name[30];

It defines an array name and reserves 30 bytes for storing characters as a single character consumes 1 byte. The last byte is used for storing the null character ‘\0’, so the total number of the character specified by the user cannot exceed 29.

#include<iostream.h>
#include<conio.h>
int main() {
 clrscr();
 char name[20];
 cout<<"Enter the nameof the person :\n";
 cin>>name;
 cout<<"Name entered was :"<<name;
 getch();
 return 0;
}
Output
Enter the name of the person Dinesh
Name entered was : Dinesh

Explanation: The above program inputs and displays the name of a person. The statement

cin>>name;

prompts the user to enter the name. The user should make sure that name should not exceed 19 characters as the last character is reserved for ‘\0’. Finally, the statement cout<<name; displays the contents of the character array name on the screen.

Strings can also be initialized. The following example shows different ways of initializing a string.

char name[7] ="DINESH;
or char name [7]={ 'D', 'I', 'N', 'E', 'S', 'H', '\0'};
or char name[]="DINESH";

In the first method of initialization, the compiler allocates space for 7 characters for array name. The first six characters are filled with D, I, N, E, S, H characters and ending with a character ‘\0’ (null character) automatically. So it will appear in memory as follows,

representation in memoryThe second method of initialization also copies the individual characters into the array name in the same way as in the previous initialization, except that the user has to explicitly specify the null character (‘\0’) to mark the end of the character array so that it can be used as a string.

However, if the user specifies the array size to be less than the number of characters during initialization, it may give you unpredictable results. For example

char name[6]={ 'D', 'I', 'N', 'E', 'S', 'H', '\0'};

In the above initialization, as there is no space in the character array for storing null character (‘\0’), it makes the array unusable as a string that causes unpredictable results during the program’s execution.

So, the above problem can be overcome by specifying the size large enough to hold all the string characters, including the null character (‘\0’). As it is always difficult to count for the exact size, so a rough approximation should follow. For example

char name[10]="DINESH";

In the above initialization, the compiler allocates space for 10 characters, where the first 7 characters are filled with D, I, N, E, S, H and end with \0. The remaining 3 spaces of the character array are filled with null characters (‘\0’) automatically—this method of initialization results in wastage of memory.

wastage of memoryA better method of initialization is to skip the character array’s size at the time of its initialization. In such a case, the compiler automatically computes its size.

char name[] = "DINESH";

The compiler sets aside memory for 7 characters for character array name large enough to store all the characters, including null character. This initialization method is useful in situations where the initialized string is very long, as calculating the length manually can be error-prone.

#include<iostream.h>
#include<conio.h>
int main() {
 char name []="Hello";
 cout<<"strinG = "<<name;
 return 0;
}
Output :
String = Hello

Inputting Multi-Word String

When you input a multi-word string using an extraction operator used with cin, it reads characters until it encounters a white space character and ignores the subsequent characters.

#include<iostream.h>
int main() {
 char name[20];
 cout<<"Enter name = ";
 cin>>name;
 cout<<"Name of person = "<<name;
 return 0;
}
Output
Enter name = Dinesh Thakur
Name of person = Dinesh

The required output is not displayed as the compiler ignores the characters after the first space. Thus, the multi-word string cannot be inputted using an >> operator in association with cin.

So to read multi-word string, use cin.get().

#include<iostream.h>
#include<conio.h>
int main() {
 clrscr();
 char name[20];
 cout<<"Enter name = ";
 cin.get(name,20);
 cout<<"Name of Person = "<<name;
 return 0;
}
Output :
Enter name = Dinesh Thakur
Name of Person = Dinesh Thakur

Explanation: In the above program, we get the expected output. The function cin.get() takes two arguments. The first corresponds to the array name, and the second corresponds to the maximum number of characters inputted. The user can input a multi-word string until the maximum number of characters is 19 (one reserved for ‘\0’) or the user enters a new line character (‘\n’).

Now let us consider another program

// Program to count frequency of vowels in a string
#include <iostream.h>
#include <conio.h>
#include <string.h>
int main() {
 clrscr();
 char str[80];
 int i,len,acount,icount,ecount,ocount,ucount;
 cout<<"Enter the string -->";
 cin.get(str,80);
 len = strlen(str);
 acount=icount=ecount=ocount=ucount=0;
 for(i=0;i<len;i++) {
   if(str[i]=='a')
     acount++;
   else if(str[i]=='e')
     ecount++;
   else if(str[i]=='i')
     icount++;
   else if(str[i]=='o')
     ocount++;
   else if(str[i]=='u')
     ucount++;
 }
cout<<"a occurs "<<acount<<" times\n";
cout<<"e occurs "<<ecount<<" times\n";
cout<<"i occurs ''<<icount<<" times\n";
cout<<"o occurs "<<ocount<<" times\n";
cout<<"u occurs "<<ucount<<" times\n";
getch(); return 0;
}
Output:
Enter the string -->welcome india
a occurs 1 times
e occurs 2 times
i occurs 2 times
o occurs 1 times
u occurs 0 times

Inputting Multi-Line String

Like multi-word strings, users can also input multi-line strings using the cin.get( ) function with little modification. It takes the following form.

get(str, MAX, delim)

Here, str is an array of characters. MAX is the maximum number of characters, and delim is the delimiter character that specifies when to stop reading. This function reads characters from the keyboard, stored in array str until either (MAX-1) characters have been read or a character specified by delim has been found.

#include<iostream.h>
#include<conio.h>
int main() {
 clrscr();
 char str[80];
 cout<<"Enter a string : \n";
 cin.get(str,80,'*');
 cout<<"String =\n"<<str;
 return 0;
}
Output :
Enter a string :
Share Index is growing.
Buy IPCI at current price*.
String=
Share Index is growing
Buy IPCI at current price

Another way to input multi-line strings is by using the getline function. This function is similar to that of get (str, MAX, delim) for inputting multi-line strings except that it removes the delimiter character from the input stream, whereas, in the case of get, it remains in the input stream until the next input operation.

Consider the following program segment.

char str[80];
cin.getline(str,80, '*');

This statement on execution can input multiple lines until either user enters the terminating character ‘*’ or until the user exceeds the size of the array.
The getline() is preferred over get() because it discards the delimiter rather than leaving it in the input stream until the next input operation.

#include <iostream.h>
#include <conio.h>
int main() {
 clrscr();
 char a[100];
 int c=0,w=1,l=1;
 cout<<"Enter the string ;";
 cin.getline(a,100,'*');
 for(int i=0;a[i]!='\0';i++) {
  if (a[i]='\n')
    {l++;w++;}
  if(a[i]==' ' && a[i+1] !=' ')
    w++;
    c++;
 }
  cout<<"Characters = "<<c;
  cout<<"\nWords ="<<w;
  cout<<"\nLines = "<<l;
  getch();
  return 0 ;
}
Output :
Enter' the string : My Name is Movis
My House number is 6886*
Characters = 40
Words = 9
Lines = 2

Explanation: In this program, we input multiple lines of a string using the cin.getline() function. Then we traverse each character of the string one by one. On encountering any space between two consecutive characters, word count w is incremented by 1. Similarly, for line count 1. Finally, count for words, characters and lines are displayed. We initialize w = 1 and 1 = 1 as we assume that each string has atleast one word and one line.

You’ll also like:

  1. C Program Using Pointers that Deletes all Occurences of a Particular Character in a String and Returns corrected String
  2. How will you define String Processing along with the different String Operations
  3. String Processing — Write out a function that prints out all the permutations of a String. For example, abc would give you abc, acb, bac, bca, cab, cba.
  4. How Convert Lower Case (strlwr) String to Upper case (strupr) String
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C++ Tutorials

C++ Tutorials

  • C++ - Data Types
  • C++ - Operators Types
  • C++ - CPP Program Structure
  • C++ - Conditional Statements
  • C++ - Loop
  • C++ - do-While Loop
  • C++ - Control Statements
  • C++ - Tokens
  • C++ - Jump Statements
  • C++ - Expressions
  • C++ - Constants
  • C++ - Character Set
  • C++ - Iteration Statements
  • C++ - I/O Statements
  • C++ - String
  • C++ - Manipulators

C++ Operator

  • C++ - Input/Output Operator
  • C++ - Operator Overloading

C++ Functions

  • C++ - Functions
  • C++ - Member Functions
  • C++ - Returning Object from Function
  • C++ - Call by Value Vs Reference
  • C++ - Friend Function
  • C++ - Virtual Function
  • C++ - Inline Function
  • C++ - Static Data Members
  • C++ - Static Member Functions

C++ Array & Pointer

  • C++ - Array
  • C++ - Array of Objects
  • C++ - Arrays as Class Members
  • C++ - Vector
  • C++ - Pointer
  • C++ - 'this' Pointer

C++ Classes & Objects

  • C++ - Class
  • C++ - Program Structure With Classes
  • C++ - OOP’s
  • C++ - Objects as Function Arguments
  • C++ - Procedure Vs OOL
  • C++ - Object Vs Class
  • C++ - Creating Objects
  • C++ - Constructors
  • C++ - Copy Constructor
  • C++ - Constructor Overloading
  • C++ - Destructor
  • C++ - Polymorphism
  • C++ - Virtual Base Class
  • C++ - Encapsulation

C++ Inheritance

  • C++ - Inheritance
  • C++ - Multiple Inheritance
  • C++ - Hybrid Inheritance
  • C++ - Abstraction
  • C++ - Overloading

C++ Exception Handling

  • C++ - Exception Handling
  • C++ - Templates
  • C++ - Standard Template Library

C++ Data Structure

  • C++ - Link List

C++ Programs

  • C++ Program for Electricity Bill
  • C++ Program for Multiply Matrices
  • C++ Program for Arithmetic Operators
  • C++ Program For Matrices
  • C++ Program for Constructor
  • C++ Program Verify Number
  • C++ Program Array Of Structure
  • C++ Program to find Average Marks
  • C++ Program Add And Subtract Matrices
  • C++ Program Menu Driven
  • C++ Program To Simple Interest
  • C++ Program To Find Average
  • C++ program exit()
  • C++ Program Using Array Of Objects
  • C++ Program Private Member Function
  • C++ Program To Reverse A String
  • C++ Program to Operator Overloading

Other Links

  • C++ - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW