Skip to main content

C++ String

C++ Strings

In C++, string is an object of std::string class that represents sequence of characters. We can perform many operations on strings such as concatenation, comparison, conversion etc.


C++ String Example

Let's see the simple example of C++ string.

  1. #include <iostream>  
  2. using namespace std;  
  3. int main( ) {  
  4.     string s1 = "Hello";    
  5.         char ch[] = { 'C''+''+'};    
  6.         string s2 = string(ch);    
  7.         cout<<s1<<endl;    
  8.         cout<<s2<<endl;    
  9. }  

Output:

Hello
C++

C++ String Compare Example

Let's see the simple example of string comparison using strcmp() function.

  1. #include <iostream>  
  2. #include <cstring>  
  3. using namespace std;  
  4. int main ()  
  5. {  
  6.   char key[] = "mango";  
  7.   char buffer[50];  
  8.   do {  
  9.      cout<<"What is my favourite fruit? ";  
  10.      cin>>buffer;  
  11.   } while (strcmp (key,buffer) != 0);  
  12.  cout<<"Answer is correct!!"<<endl;  
  13.   return 0;  
  14. }  

Output:

What is my favourite fruit? apple
What is my favourite fruit? banana
What is my favourite fruit? mango
Answer is correct!!

C++ String Concat Example

Let's see the simple example of string concatenation using strcat() function.

  1. #include <iostream>  
  2. #include <cstring>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     char key[25], buffer[25];  
  7.     cout << "Enter the key string: ";  
  8.     cin.getline(key, 25);  
  9.     cout << "Enter the buffer string: ";  
  10.      cin.getline(buffer, 25);  
  11.     strcat(key, buffer);   
  12.     cout << "Key = " << key << endl;  
  13.     cout << "Buffer = " << buffer<<endl;  
  14.     return 0;  
  15. }  

Output:

Enter the key string: Welcome to
Enter the buffer string:  C++ Programming.
Key = Welcome to C++ Programming.
Buffer =  C++ Programming.

C++ String Copy Example

Let's see the simple example of copy the string using strcpy() function.

  1. #include <iostream>  
  2. #include <cstring>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     char key[25], buffer[25];  
  7.     cout << "Enter the key string: ";  
  8.     cin.getline(key, 25);  
  9.     strcpy(buffer, key);  
  10.     cout << "Key = "<< key << endl;  
  11.     cout << "Buffer = "<< buffer<<endl;  
  12.     return 0;  
  13. }  

Output:

Enter the key string: C++ Tutorial
Key = C++ Tutorial
Buffer = C++ Tutorial

C++ String Length Example

Let's see the simple example of finding the string length using strlen() function.

  1. #include <iostream>  
  2. #include <cstring>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     char ary[] = "Welcome to C++ Programming";  
  7.     cout << "Length of String = " << strlen(ary)<<endl;  
  8.     return 0;  
  9. }  

Output:

Length of String = 26

C++ String Functions

FunctionDescription
int compare(const string& str)It is used to compare two string objects.
int length()It is used to find the length of the string.
void swap(string& str)It is used to swap the values of two string objects.
string substr(int pos,int n)It creates a new string object of n characters.
int size()It returns the length of the string in terms of bytes.
void resize(int n)It is used to resize the length of the string up to n characters.
string& replace(int pos,int len,string& str)It replaces portion of the string that begins at character position pos and spans len characters.
string& append(const string& str)It adds new characters at the end of another string object.
char& at(int pos)It is used to access an individual character at specified position pos.
int find(string& str,int pos,int n)It is used to find the string specified in the parameter.
int find_first_of(string& str,int pos,int n)It is used to find the first occurrence of the specified sequence.
int find_first_not_of(string& str,int pos,int n )It is used to search the string for the first character that does not match with any of the characters specified in the string.
int find_last_of(string& str,int pos,int n)It is used to search the string for the last character of specified sequence.
int find_last_not_of(string& str,int pos)It searches for the last character that does not match with the specified sequence.
string& insert()It inserts a new character before the character indicated by the position pos.
int max_size()It finds the maximum length of the string.
void push_back(char ch)It adds a new character ch at the end of the string.
void pop_back()It removes a last character of the string.
string& assign()It assigns new value to the string.
int copy(string& str)It copies the contents of string into another.
char& back()It returns the reference of last character.
Iterator begin()It returns the reference of first character.
int capacity()It returns the allocated space for the string.
const_iterator cbegin()It points to the first element of the string.
const_iterator cend()It points to the last element of the string.
void clear()It removes all the elements from the string.
const_reverse_iterator crbegin()It points to the last character of the string.
const_char* data()It copies the characters of string into an array.
bool empty()It checks whether the string is empty or not.
string& erase()It removes the characters as specified.
char& front()It returns a reference of the first character.
string&  operator+=()It appends a new character at the end of the string.
string& operator=()It assigns a new value to the string.
char operator[](pos)It retrieves a character at specified position pos.
int rfind()It searches for the last occurrence of the string.
iterator end()It references the last character of the string.
reverse_iterator rend()It points to the first character of the string.
void shrink_to_fit()It reduces the capacity and makes it equal to the size of the string.
char* c_str()It returns pointer to an array that contains null terminated sequence of characters.
const_reverse_iterator crend()It references the first character of the string.
reverse_iterator rbegin()It reference the last character of the string.
void reserve(inr len)It requests a change in capacity.
allocator_type get_allocator();It returns the allocated object associated with the string.



Anurag Rana

Comments

Popular posts from this blog

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are...

Genetic Algorithm: Population, Fitness Function, Parent Selection, Cross over, Mutation

Genetic Algo Population Population is a subset of solutions in the current generation. It can also be defined as a set of chromosomes. There are several things to be kept in mind when dealing with GA population − The diversity of the population should be maintained otherwise it might lead to premature convergence. The population size should not be kept very large as it can cause a GA to slow down, while a smaller population might not be enough for a good mating pool. Therefore, an optimal population size needs to be decided by trial and error. The population is usually defined as a two dimensional array of –  size population, size x, chromosome size . Population Initialization There are two primary methods to initialize a population in a GA. They are − Random Initialization  − Populate the initial population with completely random solutions. Heuristic initialization  − Populate the initial population using a known heuristic for the problem. It has been observed that the e...

C++ (Object and Class)

The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language. Object Oriented Programming is a paradigm that provides many concepts such as  inheritance, data binding, polymorphism etc. The programming paradigm where everything is represented as an object is known as truly object-oriented programming language.  Smalltalk  is considered as the first truly object-oriented programming language. OOPs (Object Oriented Programming System) Object  means a real word entity such as pen, chair, table etc.  Object-Oriented Programming  is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object Class Inheritance Polymorphism Abstraction Encapsulation C++ Object In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an ent...