C++ string class and its applications

In C++ we can store string by one of the two ways –

  1. C style strings
  2. string class (discussed in this post)

In this post, second method is discussed. string class is part of C++ library that supports a lot much functionality over C style strings.
C++ string class internally uses char array to store character but all memory management, allocation and null termination is handled by string class itself that is why it is easy to use. The length of c++ string can be changed at runtime because of dynamic allocation of memory similar to vectors. As string class is a container class, we can iterate over all its characters using an iterator similar to other containers like vector, set and maps, but generally we use a simple for loop for iterating over the characters and index them using [] operator.
C++ string class has a lot of functions to handle string easily. Most useful of them are demonstrated in below code.

// C++ program to demonstrate various function string class
#include <bits/stdc++.h>
using namespace std;
int main()
{
    // various constructor of string class
    // initialization by raw string
    string str1("first string");
    // initialization by another string
    string str2(str1);
    // initialization by character with number of occurence
    string str3(5, '#');
    // initialization by part of another string
    string str4(str1, 6, 6); // from 6th index (second parameter)
                             // 6 characters (third parameter)
    // initialization by part of another string : iteartor version
    string str5(str2.begin(), str2.begin() + 5);
    cout << str1 << endl;
    cout << str2 << endl;
    cout << str3 << endl;
    cout << str4 << endl;
    cout << str5 << endl;
    //  assignment operator
    string str6 = str4;
    // clear function deletes all character from string
    str4.clear();
    //  both size() and length() return length of string and
    //  they work as synonyms
    int len = str6.length(); // Same as "len = str6.size();"
    cout << "Length of string is : " << len << endl;
    // a particular character can be accessed using at /
    // [] operator
    char ch = str6.at(2); //  Same as "ch = str6[2];"
    cout << "third character of string is : " << ch << endl;
    //  front return first character and back returns last charcter
    //  of string
    char ch_f = str6.front();  // Same as "ch_f = str6[0];"
    char ch_b = str6.back();   // Same as below
                               // "ch_b = str6[str6.length() - 1];"
    cout << "First char is : " << ch_f << ", Last char is : "
         << ch_b << endl;
    // c_str returns null terminated char array version of string
    const char* charstr = str6.c_str();
    printf("%s\n", charstr);
    // append add the argument string at the end
    str6.append(" extension");
    //  same as str6 += " extension"
    // another version of appends, which appends part of other
    // string
    str4.append(str6, 0, 6);  // at 0th position 6 character
    cout << str6 << endl;
    cout << str4 << endl;
    //  find returns index where pattern is found.
    //  If pattern is not there it returns predefined
    //  constant npos whose value is -1
    if (str6.find(str4) != string::npos)
        cout << "str4 found in str6 at " << str6.find(str4)
             << " pos" << endl;
    else
        cout << "str4 not found in str6" << endl;
    //  substr(a, b) function returns a substring of b length
    //  starting from index a
    cout << str6.substr(7, 3) << endl;
    //  if second argument is not passed, string till end is
    // taken as substring
    cout << str6.substr(7) << endl;
    //  erase(a, b) deletes b character at index a
    str6.erase(7, 4);
    cout << str6 << endl;
    //  iterator version of erase
    str6.erase(str6.begin() + 5, str6.end() - 3);
    cout << str6 << endl;
    str6 = "This is a examples";
    //  replace(a, b, str)  replaces b character from a index by str
    str6.replace(2, 7, "ese are test");
    cout << str6 << endl;
    return 0;
}

Output :

first string
first string
#####
string
first
Length of string is : 6
third character of string is : r
First char is : s, Last char is : g
string
string extension
string
str4 found in str6 at 0 pos
ext
extension
string nsion
strinion
These are test examples

As seen in above code, we can get length of string by size() as well as length() but length() is preferred for strings. We can concat a string to another string by += or by append(), but += is slightly slower than append() because each time + is called a new string (creation of new buffer) is made which is returned that is a bit overhead in case of many append operation.

Applications :
On basis of above string function some application are written below :

// C++ program to demonstrate uses of some string function
#include <bits/stdc++.h>
using namespace std;
// this function returns floating point part of a number-string
string returnFloatingPart(string str)
{
    int pos = str.find(".");
    if (pos == string::npos)
        return "";
    else
        return str.substr(pos + 1);
}
// this function checks whether string contains all digit or not
bool containsOnlyDigit(string str)
{
    int l = str.length();
    for (int i = 0; i < l; i++)
    {
        if (str.at(i) < '0' || str.at(i) > '9')
            return false;
    }
    //  if we reach here all character are digits
    return true;
}
// this function replaces all single space by %20
// Used in URLS
string replaceBlankWith20(string str)
{
    string replaceby = "%20";
    int n = 0;
    // loop till all space are replaced
    while ((n = str.find(" ", n)) != string::npos )
    {
        str.replace(n, 1, replaceby);
        n += replaceby.length();
    }
    return str;
}
// driver function to check above methods
int main()
{
    string fnum = "23.342";
    cout << "Floating part is : " << returnFloatingPart(fnum)
         << endl;
    string num = "3452";
    if (containsOnlyDigit(num))
        cout << "string contains only digit" << endl;
    string urlex = "google com in";
    cout << replaceBlankWith20(urlex) << endl;
    return 0;     
}

Output :

Floating part is : 342
string contains only digit
google%20com%20in

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/c-string-class-and-its-applications/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Merry Christmas (Program for Christmas Tree in C)

Since Christmas is right at the door, its time to celebrate it in the programmer’s way. Lets build a decorative Christmas tree in C.

To print a Christmas tree, we are printing pyramids of various sizes just one beneath the other.
For the decoration, a random character is printed at each position.

Height and randomness can be adjusted. This is been repeated frame after frame to give the illusion of a true event.

Example:

Lets see the code.

// C program to print a  Christmas tree
// It is recommended is try it with a desktop
// compiler like CodeBlocks.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define RefRate 40000
#define randomness 5 // high means less random
// Clear the shell
voidclrscr()
{
    system("@cls||clear");
}
// Print a random character giving preference
// to *
voidprintRandLeaf()
{
    charleaftypes[5] = { '.', '*', '+', 'o', 'O'};
    inttemp = rand() % randomness;
    // Giving preference to *
    if(temp == 1)
        printf("%c ", leaftypes[rand() % 5]);
    else
        printf("%c ", leaftypes[1]);
}
voidtriangle(intf, intn, inttoth)
{
    inti, j, k = 2 * toth - 2;
    for(i = 0; i < f - 1; i++)
        k--;
    // number of rows
    for(i = f - 1; i < n; i++) {
        // space handler
        for(j = 0; j < k; j++)
            printf(" ");
        // decrementing k after each loop
        k = k - 1;
        // number of columns, printing stars
        for(j = 0; j <= i; j++)
            printRandLeaf();
        printf("\n");
    }
}
// Prints multiple triangles
voidprintTree(inth)
{
    intstart = 1, stop = 0, diff = 3;
    while(stop < h + 1) {
        stop = start + diff;
        triangle(start, stop, h);
        diff++;
        start = stop - 2;
    }
}
// Prints bottom part.
voidprintLog(intn)
{
    inti, j, k = 2 * n - 4;
    for(i = 1; i <= 6; i++) {
        // space handler
        for(j = 0; j < k; j++)
            printf(" ");
        for(j = 1; j <= 6; j++)
            printf("#");
        printf("\n");
    }
}
// Driver code
intmain()
{
    srand(time(NULL));
    intht = 6;
    printf("\n*********MERRY CHRISTMAS*********\n\n");
    // refresh loop
    while(1) {
        clrscr();
        printTree(ht);
        printLog(ht);
        usleep(RefRate);
    }
    return0;
}

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/print-decorative-christmas-tree-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

ispunct() function in C

The ispunct() function checks whether a character is a punctuation character or not.
The term “punctuation” as defined by this function includes all printable characters that are neither alphanumeric nor a space. For example ‘@’, ‘$’, etc.
This function is defined in ctype.h header file.

syntax:

int ispunct(int ch);
ch: character to be checked.
Return Value  : function return nonzero
 if character is a punctuation character;
 otherwise zero is returned. 
// Program to check punctuation
#include <stdio.h>
#include <ctype.h>
int main()
{
    // The puncuations in str are '!' and ','
    char str[] = "welcome! to TechCodeBit, ";
    int i = 0, count = 0;
    while (str[i]) {
        if (ispunct(str[i]))
            count++;
        i++;
    }
    printf("Sentence contains %d punctuation"
           " characters.\n", count);
    return 0;
}

Output:

Sentence contains 2 punctuation characters.
// C program to print all Punctuations
#include <stdio.h>
#include <ctype.h>
int main()
{
    int i;
    printf("All punctuation characters in C"
            " programming are: \n");
    for (i = 0; i <= 255; ++i)
        if (ispunct(i) != 0)
            printf("%c ", i);
    return 0;
}

Output:

All punctuation characters in C programming are: 
! " # $ % & ' ( ) * +, - . / : ;  ? @ [ \ ] ^ _ ` { | } ~

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/ispunct-function-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

strspn() function in C

The strspn() function returns the length of the initial substring of the string pointed to by str1 that is made up of only those character contained in the string pointed to by str2.

Syntax :

size_t strspn(const char *str1, const char *str2)
str1 : string to be scanned.
str2 : string containing the 
characters to match.
Return Value : This function
returns the number of characters
in the initial segment of str1 
which consist only of characters 
from str2.
// C program to illustrate strspn() function
#include <stdio.h>
#include <string.h>
int main () {
   int len = strspn("tech code tech",tech");
   printf("Length of initial segment matching : %d\n", len );   
   return(0);
}

Output:

Length of initial segment matching 4
// C program to illustrate strspn() function
#include <stdio.h>
#include <string.h>
int main () {
   int len = strspn("i am","xyz");
   printf("Length of initial segment matching : %d\n", len );
   return(0);
}

Output:

Length of initial segment matching 0

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/strspn-function-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

strcspn() in C

The C library function strcspn() calculates the length of the number of characters before the 1st occurrence of character present in both the string.
Syntax :

strcspn(const char *str1, const char *str2)

Parameters:
str1 : The Target string in which search has to be made.
str2 : Argument string containing characters
to match in target string.

Return Value:
This function returns the number of characters before the 1st occurrence
of character present in both the string.
// C code to demonstrate the working of
// strcspn()
#include <stdio.h>
#include <string.h>
int main()
{
    int size;
    // initializing strings
    char str1[] = "geeksforgeeks";
    char str2[] = "kfc";
    // using strcspn() to calculate initial chars
    // before 1st matching chars.
    // returns 3
    size = strcspn(str1, str2);
    printf("The unmatched characters before first matched character :  %d\n", size);
}

Output:

The unmatched characters before first matched character :  3

Practical Application : There can be many practical application of this function, be itword games or irregularity calculator. A simple word game is demonstrated in this article.

Rules : According to this game, 2 players play and one player initially generated a string and is asked to produce a string which has as many unmatched characters. After 1 round, player producing string with maximum unmatched characters wins.

// C code to demonstrate the application of
// strcspn()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int score1 = 0, score2 = 0, k = 0, sizen = 0, size = 0;
    // initial Round1 strings
    char player1[] = "geeks";
    char play2[] = "";
    while (1) {
        // generating random character
        char randoml = 'a' + (random() % 26);
        play2[k++] = randoml;
        size = strcspn(play2, player1);
        if (size == sizen) {
            // if the character is present, break
            score2 = size;
            break;
        }
        else {
            sizen = size;
        }
    }
    // initial Round2 strings
    const char player2[] = "geeks";
    char play1[] = "";
    k = 0, sizen = 0;
    while (1) {
        // generating random character
        char randoml = 'a' + (random() % 26);
        play1[k++] = randoml;
        size = strcspn(play1, player2);
        if (size == sizen)
{
            // if the character is present, break
            score1 = size;
            break;
        }
        else {
            sizen = size;
        }
    }
    if (score1 > score2)
        printf("Player 1 won!! Score : %d", score1);
    else if (score2 > score1)
        printf("Player 2 won!! Score : %d", score2);
    else
        printf("Match Drawn!! Score : %d", score1);
}

Output:

Match Drawn!! Score : 2

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/strcspn-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Modulus on Negative Numbers

What will be the output of the following C program?

#include <stdio.h>
int main()
{
   int a = 3, b = -8, c = 2;
   printf("%d", a % b / c);
   return 0;
}

Output

1

% and / have same precedence and left to right associativity. So % is performed first which results in 3 and / is performed next resulting in 1. The emphasis is, sign of left operand is appended to result in case of modulus operator in C.

#include <stdio.h>
int main()
{
   // a positive and b negative.
   int a = 3, b = -8;
   printf("%d", a % b);
   return 0;
}

Output

-3
#include <stdio.h>
int main()
{
   // a negative and b positive
   int a = -3, b = 8;
   printf("%d", a % b);
   return 0;
}

Output

3
#include <stdio.h>
int main()
{
   // a and b both negative
   int a = -3, b = -8;
   printf("%d", a % b);
   return 0;
}

Output

-3

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/modulus-on-negative-numbers/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Precedence of postfix ++ and prefix ++ in C/C++

In C/C++, precedence of Prefix ++ (or Prefix –) and dereference (*) operators is same, and precedence of Postfix ++ (or Postfix –) is higher than both Prefix ++ and *.

If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right associative).

For example, program 1 prints ‘h’ and program 2 prints ‘e’.

// Program 1
#include<stdio.h>
int main()
{
  char arr[] = "techcodebit";
  char *p = arr;
  ++*p;
  printf(" %c", *p);
  getchar();
  return 0;
}

Output: u

// Program 2
#include<stdio.h>
int main()
{
  char arr[] = "techcodebit";
  char *p = arr;
  *p++;
  printf(" %c", *p);
  getchar();
  return 0;
}

Output: s

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/g-fact-59/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Order of operands for logical operators

The order of operands of logical operators &&, || are important in C/C++.

In mathematics, logical AND, OR, etc… operations are commutative. The result will not change even if we swap RHS and LHS of the operator.

In C/C++ (may be in other languages as well)  even though these operators are commutative, their order is critical. For example see the following code,

// Traverse every alternative node
while( pTemp && pTemp->Next )
{
   // Jump over to next node
   pTemp = pTemp->Next->Next;
}

The first part pTemp will be evaluated against NULL and followed by pTemp->Next. If pTemp->Next is placed first, the pointer pTemp will be dereferenced and there will be runtime error when pTemp is NULL.

It is mandatory to follow the order. Infact, it helps in generating efficient code. When the pointer pTemp is NULL, the second part will not be evaluated since the outcome of AND (&&) expression is guaranteed to be 0.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/g-fact-74/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

Result of comma operator as l-value in C and C++

Using result of comma operator as l-value is not valid in C. But in C++, result of comma operator can be used as l-value if the right operand of the comma operator is l-value.

For example, if we compile the following program as a C++ program, then it works and prints b = 30. And if we compile the same program as C program, then it gives warning/error in compilation (Warning in Dev C++ and error in Code Blocks).

#include<stdio.h>
int main()
{
  int a = 10, b = 20;
  (a, b) = 30; // Since b is l-value, this statement is valid in C++, but not in C.
  printf("b = %d", b);
  getchar();
  return 0;
}

Output:
b = 30

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/g-fact-78/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

 

Catch block and type conversion in C++

Predict the output of following C++ program.

#include <iostream>
using namespace std;
int main()
{
    try
    {
        throw 'x';
    }
    catch(int x)
    {
        cout << " Caught int " << x;
    }
    catch(...)
    {
        cout << "Defaule catch block";
    }
}
Defaule catch block

In the above program, a character ‘x’ is thrown and there is a catch block to catch an int. One might think that the int catch block could be matched by considering ASCII value of ‘x’. But such conversions are not performed for catch blocks. Consider the following program as another example where conversion constructor is not called for thrown object.

#include <iostream>
using namespace std;
class MyExcept1 {};
class MyExcept2
{
public:
    // Conversion constructor
    MyExcept2 (const MyExcept1 &e )
    {
        cout << "Conversion constructor called";
    }
};
int main()
{
    try
    {
        MyExcept1 myexp1;
        throw myexp1;
    }
    catch(MyExcept2 e2)
    {
        cout << "Caught MyExcept2 " << endl;
    }
    catch(...)
    {
        cout << " Defaule catch block " << endl;
    }
    return 0;
}
Defaule catch block

As a side note, the derived type objects are converted to base typr when a derived object is thrown and there is a catch block to catch base type.

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:https://www.geeksforgeeks.org/catch-block-and-type-conversion-in-c/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide