Table of contents
1.
Introduction 
2.
How to Take String Input in C++
3.
Other Ways to Define a String in C++
4.
How to Take String Input in C++ with Examples?
4.1.
Example 1: Single-word input using cin
4.2.
C++
4.3.
Example 2: Multi-word input using getline()
4.4.
C++
5.
How to Pass Strings to Functions?
6.
Pointers and Strings
7.
Difference between String and Character Array in C++
8.
Common String Functions in C++:
8.1.
String length example in C++
8.1.1.
Code
8.2.
C++
8.3.
String Copy Example in C++
8.3.1.
Code 
8.4.
C++
8.5.
String Concat Example in C++
8.5.1.
Code 
8.6.
C++
8.7.
String Compare Example in C++
8.7.1.
Code
8.8.
C++
9.
C++ String Functions
10.
Frequently asked questions
10.1.
What are the string functions in C++?
10.2.
Which string function is used for the concatenation of two strings?
10.3.
Which header file is required for string functions in C++?
11.
Conclusion
Last Updated: Nov 30, 2024
Easy

C++ Strings

Author Akash
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

Before knowing about string functions, we have to know about string. In C++ string is an object of a string class representing the sequence of characters. String functions are nothing, just functions that are used to perform operations on a string. To use these string functions in C++, you need to add a library named <string> in your code at the top, which gives you various string functions like strlen, strcmp, strcat, swap, strcpy, and many more. 

Strings in C++

Fibonacci Series in C++

How to Take String Input in C++

To take string input in C++, you can use the cin object for single-word input and getline() for multi-word input.

  1. Using cin: cin reads input until the first whitespace character. It's suitable for single-word strings.
  2. Using getline: getline() reads an entire line, including spaces, until a newline character.

Other Ways to Define a String in C++

In C++, strings can be defined using the following methods:

1. Using the std::string class:
The std::string class from the <string> header provides dynamic string manipulation.

string str = "Hello, World!";

 

2. Using character arrays:
Character arrays provide static string definition, but are less flexible than std::string.

char str[] = "Hello, World!";

 

3. Using pointers:
Strings can also be defined as pointers to character literals.

const char* str = "Hello, World!";

How to Take String Input in C++ with Examples?

Example 1: Single-word input using cin

  • C++

C++

#include <iostream>
using namespace std;

int main() {
string word;
cout << "Enter a word: ";
cin >> word;
cout << "You entered: " << word << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Example 2: Multi-word input using getline()

  • C++

C++

#include <iostream>
using namespace std;

int main() {
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
cout << "You entered: " << sentence << endl;
return 0;
}
You can also try this code with Online C++ Compiler
Run Code

How to Pass Strings to Functions?

Strings in C++ can be passed to functions in several ways:

1. Pass by value:
A copy of the string is passed, and changes in the function do not affect the original string.

void printString(string str) {
    cout << "String: " << str << endl;
}

 

2. Pass by reference:
The original string is passed, allowing modifications.

void modifyString(string &str) {
    str += " World!";
}

 

3. Pass by pointer:
A pointer to the string is passed, allowing modifications.

void printString(const string* str) {
    cout << "String: " << *str << endl;
}

Pointers and Strings

Pointers can be used to handle strings in C++. A pointer can reference a string literal or a dynamic string.

1. Pointer to a character array:

const char* str = "Hello";
cout << str;

 

2. Pointer to a dynamic string:

string* ptr = new string("Dynamic String");
cout << *ptr;
delete ptr;  // Free memory

Pointers enable efficient string manipulation but require careful memory management.

Difference between String and Character Array in C++

Parametersstd::stringCharacter Array
Header File<string>None
MutabilityDynamic size, can grow/shrinkFixed size, predefined
Ease of UseEasier with built-in methodsRequires manual operations
Memory ManagementHandled automaticallyNeeds manual management
FunctionalityRich with built-in functionsLimited functions available
PerformanceSlightly slowerFaster for fixed-size data

Common String Functions in C++:

  • strlen(str1): It is used to find the length of a string.
  • strcpy(str1,str2): It is used to copy the content of a string into another.
  • strcat(str1,str2): It is used to append two strings.
  • strcmp(str1,str2): this string function returns negative value if str1 is less than str2, 0 if str1 is equal to str2, and positive value if str1 is greater than str2.
  • substr(starting index, from that index how many characters you want): It is used to take the substring from the given string.
     

Now we will discuss how to use the string function in C++ with the help of some examples.

String length example in C++

Here is a simple example of finding the string length using strlen(),size() and length() functions.

Code

  • C++

C++

// C++ Program to demonstrate the working of strlen(), size() and length()
#include<iostream>
#include<string.h>  // for string class
using namespace std;
int main()
{
   // Initializing the string
   char str1[]="codingninjas";
   string str2="string functions are very useful";
   cout<<"The length of the first string using strlen(): ";
   cout<<strlen(str1)<<endl;
   cout<<"The length of the second string using size(): ";
   cout<<str2.size()<<endl;
   cout<<"The length of the second string using length(): ";
   cout<<str2.length()<<endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output 

The length of the first string using strlen(): 12
The length of the second string using size(): 32
The length of the second string using length(): 32

String Copy Example in C++

Here is a simple example of copying the string using strcpy() function.

Code 

  • C++

C++

// Simple C++ Program to demonstrate the working of strcpy()
#include<iostream>
#include<string.h>  // for string class
using namespace std;
int main()
{
   // Initializing the string
   char str1[50]="Coding Ninjas";
   char str2[50];
   strcpy(str2,str1);
   cout<<"The value of the first string is: ";
   cout<<str1<<endl;
   cout<<"The value of the second string is: ";
   cout<<str2<<endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output 

The value of the first string is: Coding Ninjas
The value of the second string is: Coding Ninjas

String Concat Example in C++

Here is a simple example of the string concatenation using Strcat() function

Code 

  • C++

C++

// C++ Program to demonstrate the working of strcat()
#include<iostream>
#include<string.h>  // for string class
using namespace std;
int main()
{
   // Initializing the string
   char str1[]="Coding";
   char str2[]=" Ninjas";
   strcat(str1,str2);
   cout<<"The value of the first string is: ";
   cout<<str1<<endl;
   cout<<"The value of the second string is:";
   cout<<str2<<endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

The value of the first string is: Coding Ninjas
The value of the second string is: Ninjas

 

Try and compile with online c++ compiler.

String Compare Example in C++

Here is a simple example of the string comparison using strcmp() function.

Code

  • C++

C++

// C++ Program to demonstrate the working of strcmp()
#include<iostream>
#include<string.h>  // for string class
using namespace std;
int main()
{
   // Initializing the string
   char str1[]="Coding";
   char str2[]="Coding";
   int res=strcmp(str1,str2);
   cout<<res<<endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

0

In the above code, the res is 0. This means that both the strings are the same.

C++ String Functions

Here is a list of the string functions with their use.

String Functions

Description

getline()This function is used to read a string or a line from an input stream.
push_back(char ch)This function inserts a new character ch at the end of the string.
pop_back()This function removes the last character of the string.
size()This function returns the size of the string in terms of bytes.
length()This function is used to find the length of the string.
substr(int pos, int n)This function creates a new string object of n character.
c_str()This function returns a pointer to an array that contains a null-terminated sequence of characters.
empty()This function is used to check whether a string is empty or not.
clear()This function is used to remove all elements from the string.
resize(int n)This function is used to resize the length of a string.
capacity()This function returns the allocated space of the string.
begin()This function returns the reference of the first character.
end()This function returns the reference of the last character.
max_size()This function returns the maximum length of the string.
at(int k)This function is used to access an individual character at specified position k.
swap(string& str)This function is used to swap the values of two strings.
shrink_to_fit()This function decreases the capacity of the string and makes it equal to the size of the string.

Also check out - Substr C++

Frequently asked questions

What are the string functions in C++?

String functions are nothing, just functions that are used to perform operations on a string.

Which string function is used for the concatenation of two strings?

strcat(str1, str2) function is used to concatenate two strings.

Which header file is required for string functions in C++?

<string.h> is the header file required for string functions in C++.

Conclusion

Strings in C++ offer flexibility and versatility, making them essential for handling textual data in programs. With options like the dynamic std::string class and static character arrays, developers can choose the approach that best suits their needs. Whether taking input, passing strings to functions, or working with pointers, C++ provides robust tools for string manipulation. Understanding the differences and use cases of std::string and character arrays ensures better performance and more maintainable code.

You can learn more about such programming concepts here.

Recommended problems -

This blog is over, but learning never stops, and there is a lot more to learn. Have a nice day and Happy Coding!  

Live masterclass