Character Array Vs String Class in C++

Character Array and String Class are the two important topics of the C++ programming language and have their own use in many different situations. Both are used to deal with sequences of characters but many people get confused about finding the difference between them and when to use which one. 

String Class in C++ is introduced because there were many drawbacks to Character Array and you will be able to find it when you will read the difference between Character Array and String Class.

Character Array String Class
A character Array is an array used to store character-type data.

Ex: char ch[4] = "abc";
A string is a class in C++ programming and the string type variable is basically the object of the string class.

Ex: string str = "algolesson";
In character Array, we need to know the size of an array in advance. It string there is no need to know the size in advance. They adjust their size based on the requirement.
We cannot use C++ Operator on Character Array. We can use C++ Operator on String Class.
Operations like concatenation or append are difficult as a larger size Char array is required. An operation like concatenation or append are easier change in string size takes place automatically.
Character Arrays are much faster. Strings are slower as compared to the character array.

Example of Character Array code in C++:
//C++ example program for Character Array
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[]{"Algolesson"};

  cout<<ch<<endl;
  ch[4] = 'L';
  for(int i = 0; i < 11; i++){
    cout<<ch[i];
  }
  return 0;
}
Output:
Algolesson
AlgoLesson


The drawback of Character Array.

The main drawback of the Character array is that it fails to operate with the standard operators of C++ and they are not dynamic in nature as their sizes are fixed in advance and cannot change at run time. 
char ch1[]{"algolesson"}; //OK
ch1 = "coding"; //error- not OK

char ch2[]{"welcome"};
ch2 = ch1 + ch2; //error - we cannot use operator
  • Once the Character array is initialized with a set of characters then it cannot be initialized again with a different set of characters.
  • We cannot use + operators on Character Arrays in C++.

Although these above drawbacks of character array is removed in string class where we can easily increase our string size at run time and we can use several operators on string for comparison and manipulation task. There are many string member functions available in which helps us to perform operations on strings.

Example of String Class in C++:
//C++ example program for String Class
#include<iostream>
#include<string>
using namespace std;

int main(){
  string str1 = "Welcome to ";
  string str2 = "Algolesson";

  cout<<str1<<endl;
  cout<<str2<<endl;
  cout<<"Size of str1: "<<str1.size()<<endl;
  str1 = str1 + str2; //concatenation
  cout<<str1<<endl;
  cout<<"Size of str1: "<<str1.size()<<endl;

  return 0;
}
Output:
Welcome to 
Algolesson
Size of str1: 11
Welcome to Algolesson
Size of str1: 21

In the above code, we can observe that we can easily use operators on string data type and the size of str1 get automatically change after concatenation operation. This is how string class help us to overcome from the drawbacks of Character Array.

Next:

Difference Between Subarrays, Subsequences and Subsets.

In this post, we are going to understand the basic difference between Subarrays, Subsequences, and Subsets with respect to the Array data structure. These three terms are often used in coding problems and confused many of us which makes the question more difficult to understand. Let's discuss each term one by one with examples:


Subarrays: 

A subarray is a contiguous part of the main array in which the elements of the subarray are together and next to each other in relative order. If the given array has n number of elements then there can be n*(n + 1)/2 number of non-empty subarrays possible.

Example of Subarrays:

Given arr[ ] = {3, 5, 7, 2}
Total number of elements n = 4
The number of subarrays possible = n*(n+1)/2 = 4*(4+1)/2 = 4*5/2 = 10

List of all possible subarrays:
[3]
[5]
[7]
[2]
[3, 5]
[5, 7]
[7, 2]
[3, 5, 7]
[5, 7, 2]
[3, 5, 7, 2]


Subsequences:

A subsequence of an array contains elements in a relative order but need not to be a contiguous part of the main array. If the given array has n number of elements then there can be(2^n - 1)non-empty possible subsequences.

Example of Subsequences:
Given arr[ ] = {3, 5, 7, 2}
Total number of elements n = 4
The number of subsequences possible = 2^n - 1 = 2^4 - 1 = 15

List of all possible subsequences:
[3]
[5]
[7]
[2]
[3, 5]
[3, 7]
[3, 2]
[5, 7]
[5, 2]
[7, 2]
[3, 5, 7]
[3, 5, 2]
[3, 7, 2]
[5, 7, 2]
[3, 5, 7, 2]

Subsets:

The elements of a subset do not follow any relative order and may or may not be a contiguous part of the main array. If the given array has n number of elements then there can be(2^n) number of subsets possible. 

  • If array A is a subset of another array B then it means all the elements of array A must be present in array B. A ⊆ B

Example of Subsets:
Given A[] = {2, 3, 5} and B[] = {1, 2, 3, 4, 5, 6}

A ⊆ B as all the elements of A is present in B
Note: Every Subarray is a Subsequence and every Subsequence is a Subset but vice-versa is not true. (alert-success)


Next:

(getButton) #text=(Array Data Structure in C/C++) #icon=(link) #color=(#2339bd)

 

Program to Print Pascal's Triangle in Pattern.

Pascal Triangle is basically a triangular array formed by Binomial Coefficients. Here in this post, we will learn how to print Pascal Triangle using C++ programming language. Before going to the code section let us first understand the formation of the pascal triangle with one example.

Example of Pascal Triangle

If you observe the above triangular pattern carefully then you will observe that there is a rule for creating this Pascal Triangle. 
The rule for creating a Pascal Triangle is to start with the number 1 at level 0 and to get your next number for the following levels you need to add the two consecutive numbers that are present on the above left and above right side of it. (alert-success)
 1    2
 \ + /
 3

Approach 1: Using O(n^2) extra space.

Here we are going to use one extra 2D array to store the previously generated values so we can use them to calculate binomial coefficient values for the next upcoming rows. Sum the two above two consecutive numbers to get the next number.


C++ Code for Printing Pascal Triangle:

//C++ Program to Print Pascal Triangle using O(n^2) extra space
#include<iostream>
using namespace std;

void pascalTriangle(int n){
    int arr[n][n];

    cout<<"Print Pascal Triangle: "<<endl;
    for(int i = 0; i < n; i++){
        for(int j = 1; j < (n - i); j++){
            cout<<" ";
        }
        for(int k = 0; k <= i; k++){
            if(i == k || k == 0){
                arr[i][k] = 1;
            }
            else{
                arr[i][k] = arr[i - 1][k - 1] + arr[i - 1][k];
            }
            cout<<" "<<arr[i][k];
        }
        cout<<"\n";
    }
}
int main(){
    int n = 5;
    pascalTriangle(n);
}
Output:
Print Pascal Triangle:  
                  1
 
               1      1
 
            1      2      1
 
         1      3      3      1
 
      1      4      6      4      1
  • Time Complexity: (n^2)
  • Space Complexity: (n^2)

Approach 2: Without using extra Space.

Here we are simply using going to run two nested loops and going to calculate the binomial coefficient using the below formula in the inner loop. 
binomial coefficient

 C++ Code for Printing Pascal Triangle:

//Print Pascal Triangle in without using extra space in C++
#include<iostream>
using namespace std;

void pascalTriangle(int n){
    int row = n;

    cout<<"Print Pascal Triangle: "<<endl;;
    for(int i = 0; i < row; i++){
        int value = 1;
        for(int j = 1; j < (row -i); j++){
            cout<<" ";
        }
        for(int k = 0; k <= i; k++){
            cout<<" "<<value;
            value = value * (i - k)/(k + 1);
        }
        cout<<endl<<endl;
    }
}

int main(){
    int n = 5;
    pascalTriangle(n);

    return 0;
}
Output:
Print Pascal Triangle:  
                  1
 
               1      1
 
            1      2      1
 
         1      3      3      1
 
      1      4      6      4      1
  • Time Complexity: (n^2)
  • Space Complexity: (1)
I hope you found this post useful, please do share your valuable feedback in the comment section below and help us improve our content for you.

Next:

Character Functions in C++

Character Functions in C++
Character functions are those in-built functions present in the C++ programming language that help us to process characters in a string. These functions are present in the <cctype> header file. These functions can be classified into two types: Classification functions and Transformation functions

Below is the list of Character Functions with their usage in programming:
Classification Function Definition
isalnum(ch) This function returns true if the character ch is a letter or a digit.
isalpha(ch) This function returns true if the character ch is a letter.
iscntrl(ch) This function returns true if the character ch is a control character. (Ex: \t, \n, \b, \r)
isdigit(ch) This function returns true if the character ch is a digit.
isgraph(ch) This function returns true if the character ch is not a space but a printable value.
islower(ch) This function returns true if the character ch is a lowercase letter.
isupper(ch) This function returns true if the character ch is an uppercase letter.
isprint(ch) This function returns true if the character ch is a printable character.
ispunct(ch) This function returns true if the character ch is a punctuation character. (Ex: !, #, $, @)
isspace(ch) This function returns true if the character ch is whitespace.
isblank(ch) This function returns true if the character ch is blank.
isxdigit(ch) This function returns true if the character ch is a hexadecimal digit.
Transformation Function Definition
tolower(ch) This function is used to change character ch to lowercase if it is an uppercase letter otherwise leave it unchanged.
toupper(ch) This function is used to change character ch to uppercase if it is a lowercase letter otherwise leave it unchanged.

These in-built character functions take a single character as a parameter and return a value that can either be a boolean type value if it is a Classification function or a character type value if it is a Transformation function.

Let's discuss each character function with C++ example code:
1. isalnum(): This function returns true if the character is an alphabet or a number else it will return false. It is known as alphanumeric and includes characters from a-z, A-Z, and 0-9.

Example code:
/*C++ program to check isalnum() function*/
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[10] = "12Abc@";

  //working of isalnum() function
  for(int i = 0; i < 6; i++){
    if(isalnum(ch[i]))
      cout<<ch[i]<<" is an alphanumeric character."<<endl;
    else
      cout<<ch[i]<<" is not an alphanumeric character."<<endl;  
  }
  return 0;
}
Output:
1 is an alphanumeric character.
2 is an alphanumeric character.
A is an alphanumeric character.
b is an alphanumeric character.
c is an alphanumeric character.
@ is not an alphanumeric character.

2. isalpha(): This function returns true if the character is an alphabet else it returns false. It includes characters from a-z and A-Z.

Example code:
/*C++ program to check isalpha() function*/
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[10] = "1Ab@";

  //working of isalpha() function
  for(int i = 0; i < 4; i++){
    if(isalpha(ch[i]))
      cout<<ch[i]<<" is an alphabet character."<<endl;
    else
      cout<<ch[i]<<" is not an alphabet character."<<endl;  
  }
  return 0;
}
Output:
1 is not an alphabet character.
A is an alphabet character.
b is an alphabet character.
@ is not an alphabet character.

3. iscntrl(): This function returns true if the character is a control character like \t, \n, \b, \r, etc else returns false.

Example code:
// C++ program to check iscntrl()
#include <cctype>
#include <iostream>
using namespace std;

int main(){
	char ch[5] = "\nA\t\b";

	//working of iscntrl() function
	for (int i = 0; i < 4; i++) {
	   if (iscntrl(ch[i]))
		cout<<"Character is a control Character"<<endl;
	   else
		cout<<"Character is a not control Character"<<endl;		
	}
        return 0;
}
Output:
Character is a control Character
Character is a not control Character
Character is a control Character
Character is a control Character

4. isdigit(): This function returns true if the character is a digit else it returns false. It includes all digits from 0 to 9

Example code:
//C++ program to check isdigit() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[5] = "A123";

  //working of isdigit()
  for(int i = 0; i < 4; i++){
    if(isdigit(ch[i]))
      cout<<ch[i]<<" is a digit."<<endl;
    else
      cout<<ch[i]<<" is not a digit."<<endl;  
  }
  return 0;
}
Output:
A is not a digit.
1 is a digit.
2 is a digit.
3 is a digit.

5. isgraph(): This function returns true if the character is a graphical character else it returns false. Graphical characters include digits (0-9), alphabets (a-z and A-Z), and punctuation characters (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~).

Example code:
//C++ program to check isgraph() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[5] = "$\tA2";

  //working of isgraph()
  for(int i = 0; i < 4; i++){
    if(isgraph(ch[i]))
      cout<<ch[i]<<" is a graphical character."<<endl;
    else
      cout<<ch[i]<<" is not a graphical character."<<endl;  
  }
  return 0;
}
Output:
$ is a graphical character.
  is not a graphical character.
A is a graphical character.
2 is a graphical character.

6. islower(): This function returns true if the character is a lowercase letter (a-z) else it returns false.

7. isupper(): This function returns true if the character is an uppercase letter (A-Z) else it returns false.

Example code:
//C++ program to check islower() and isupper() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[5] = "ABcd";

  //working of isupper() and islower()
  for(int i = 0; i < 4; i++){
    if(islower(ch[i]))
      cout<<ch[i]<<" is a lowercase character"<<endl;
    if(isupper(ch[i]))
      cout<<ch[i]<<" is an uppercase character"<<endl;  
  }
  return 0;
}
Output:
A is an uppercase character
B is an uppercase character
c is a lowercase character
d is a lowercase character

8. isprint(): This function returns true if the character is a printable character else it returns false. All characters are printable character except the control characters. 

Example code:
//C++ program to check isprint() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[6] = "A\tBc1";

  //working of isprint()
  for(int i = 0; i < 5; i++){
    if(isprint(ch[i]))
      cout<<ch[i]<<" is a printable character"<<endl;
    else
      cout<<ch[i]<<" is not a printable character"<<endl;  
  }
  return 0;
}
Output:
A is a printable character
  is not a printable character
B is a printable character
c is a printable character
1 is a printable character 

9. ispunct(): This function returns true if the character is a punctuation character else it returns false.

Example code:
//C++ program to check ispunct() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[7] = ")#!\t2'";

  //working of ispunct()
  for(int i = 0; i < 6; i++){
    if(ispunct(ch[i]))
      cout<<ch[i]<<" is a punctuation character"<<endl;
    else
      cout<<ch[i]<<" is not a punctuation character"<<endl;  
  }
  return 0;
}
Output:
) is a punctuation character
# is a punctuation character
! is a punctuation character
  is not a punctuation character
2 is not a punctuation character

10. isspace(): This function returns true if the character is a tab or a whitespace else it returns false.

Example code: 
//C++ program to check isspace() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[7] = "A\n\t#2";

  //working of isspace()
  for(int i = 0; i < 5; i++){
    if(isspace(ch[i]))
      cout<<"Character is a space character"<<endl;
    else
      cout<<"Character is not a space character"<<endl;  
  }
  return 0;
}
Output:
Character is not a space character
Character is a space character
Character is a space character
Character is not a space character
Character is not a space character

11. isblank(): This function returns true if the character is a blank character like a space or a tab else it returns false. 

Example code:
//C++ program to check isblank() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[7] = " \n\t2";

  //working of isblank()
  for(int i = 0; i < 4; i++){
    if(isblank(ch[i]))
      cout<<"Character is a blank character"<<endl;
    else
      cout<<"Character is not a blank character"<<endl;  
  }
  return 0;
}
Output:
Character is a blank character
Character is not a blank character
Character is a blank character
Character is not a blank character

12. isxdigit(): This function returns true if the character is a hexadecimal character else it returns false. It includes characters from 0-9 and (A-F) in both uppercase and lowercase.

Example code:
//C++ program to check isxdigit() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch[7] = "AB120X";

  //working of isxdigit()
  for(int i = 0; i < 6; i++){
    if(isxdigit(ch[i]))
      cout<<ch[i]<<" is a Hexadecimal character"<<endl;
    else
      cout<<ch[i]<<" is not a Hexacecima character"<<endl;  
  }
  return 0;
}
Output:
A is a Hexadecimal character
B is a Hexadecimal character
1 is a Hexadecimal character
2 is a Hexadecimal character
0 is a Hexadecimal character
X is not a Hexacecima character

13. toupper(): This is a transformation function that change the character to uppercase letter if a lowercase character is pass to this function and if the character is already an uppercase character then no change take place.

14. tolower(): This is a transformation function that change the character to lowercase letter if an uppercase character is pass to this function and if the character is already a lowercase character then no change take place.

Example code:
//C++ program to check tolower() and toupper() function
#include<iostream>
#include<cctype>
using namespace std;

int main(){
  char ch1[11] = "welcome";
  char ch2[11] = "ALGOLESSON";
  //converting to uppercase
  for(int i = 0; i < 7; i++){
    cout<<(char)toupper(ch1[i]);
  }
  cout<<"\t";
  //converting to lowercase
  for(int i = 0; i < 10; i++){
    cout<<(char)tolower(ch2[i]);
  }
  return 0;
}
Output:
WELCOME algolesson

So here ends the complete list of built-in character functions in C++ programming language with example code to make you understand working of each function. These functions are very helpful for solving several string related coding problems.

Next:
  

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson