Focusing on strings in C++ and Operation on strings

Focusing on strings in C++.

Declaring and Initializing Different type of Strings:

Focus:String is nothing but just a sequence/Array  of characters,like “hello !! hope you are good well”.Basically C++ includes concepts of both C and C++ also.

As shown in Diagram a simple way to declare and define  a string is :

char s[20]=”hello”;                      //1st type 

char s[20]=”how are you?”;       // 2nd type

char s[20]={‘h’,’e’,’l’,’l’,’o’,’\0′};  //3rd type

While initializing third type of strings we have  to assign null characters also at the last as in 1st and second type compiler will automatically last Index of string to null characters.but when we are individually assigning each and every character we need to assign need character in last as done here char s[20]={‘h’,’e’,’l’,’l’,’o’,’\0′};

These declaration are called as C style strings.But these are not quite efficient and using inbuilt functions of strings are complex.So for using strings in C++, C++ implemented and designed a c++ string.h library where string class is defined and implemented.

C++ String Class

Declaration  and initialization C++ string Object can be done in 3 ways:

  • string x(“high school”);
  • string x= “high school”;
  • string x; x=“high school”;

Below we will be Discussing Various Operations on Strings:Just an abstract overview of concepts we will be discussing further:

Available Operation & functions  on strings /String Characteristics

  • Creating string objects.
  • Reading string objects from keyboard.
  • Displaying string objects to the screen.
  • Finding a substring from a string.
  • Modifying string objects.
  • Adding string objects.
  • Accessing characters in a string.
  • Obtaining the size of string.
  • And many more.

Reading and Displaying Strings.

string s1;

or

char s1[20];

cin >> s1;  // Reading from keyboard (one word)

cout << s1;  // Display the content of s1

getline(cin, s1);  // Reading from keyboard a line of text

A string program to  create a string object and to concatenate two or more MIXED TYPE  type of strings.

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    string w="senior"; //declaring & assigning string object:method1
    string x("secondary");//declaring & assigning string object:method2
    char y[]="school";//normal string 
    char z[]={'w','a','s',''};//normal string:when initialized in single quote
    char *p="good";
    string s=w+" "+x+" "+y+" "+z+ "  " +"very"+" "+p;//concatenating diff. types of string
    cout<<"s="<<s<<endl;
    getch();
    return 0;
}

Here in the above program we created different types of strings and have seen concatenation of Mixed-Style Strings that all the strings can be concatenated directly without using any inbuilt function.

Comparision of two strings

Comparison Operators of String Objects

We can compare two strings s and s1 using the following operators: ==, !=, <, <=, >, >=

The comparison is alphabetical not based on size of string.Comparison is done by comparing the ASCII values.

The outcome of each comparison is: true or false

The comparison works as long as at least x or y is a string object. The other string can be a string object, a C-style string variable, or a double-quoted string.

 

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
int main()
{    string x ="Health is wealth";
    char y[5];
    char *p="Do Good have Good";
    cin>>y;
    if(x<y)
    cout<<(x<y)<<endl;
    if (x<"Tit for Tat")
    cout<<"x<Tit for Tat"<<endl;
    if("Hello"!=x)
    cout<<"Hello!=X"<<endl;
    if(p>x)
    cout<<"p>x"<<endl;
    else
    cout<<"p<x";
    getch();
    return 0;
}

Converting Uppercase to lower case and vice versa using C++ string function

We can convert Lowercase string objects to uppercase string object and vice versa by using String function.String function used is :

toupper(string_name)

tolower(string_name)

#include<iostream>
#include<conio.h>
#include<string.h>
#include<ctype.h>
using namespace std;
int main()
{
string s=" Sun Rises from the East ";//string object
char s1[10]= " hello ";//string of characters
int i=0;

cout<<s;

for(i=0;s[i]!='';i++)
{
s[i]=toupper(s[i]) ;//string function when string object is used
}
cout<<"string object converted to uppercase"<<s<<endl;
cout<<"normal string converted to uppercase"<<strupr(s1)<<endl;//string function when normal string is used

for(i=0;s[i]!='';i++)
{
s[i]=tolower(s[i]);//string function when string object is used 
}
cout<<s<<endl;
cout<<strlwr(s1)<<endl;
getch();
return 0;
}

 

Creating a new substring from a Original string.

Here I declared   two  strings s1 and s2.I initialised s1 , and i wants to create sub  string s2   =”Keep Smiling” ,from string s1 only.Means substring s2 is created from string s1 only by  using  function:

String s1=”Be positive and Keep Smiling”;

String s2;

 


ing this function s1 value becomes “KeepSmiling”

This function includes two values :

pos: pos   is  Index of string s1, from where  “keep smiling” starts in string s1. Default value of position starts from ZERO.

len: is the total number of characters i need to extract,as strength of “keep smiling” is 12.

NOW

Logically, a substring of a string x is a subsequence of consecutive characters in x

For example, “rod” is a substring of “product”

If x is a string object, and we want the substring that begins at position pos and has len characters (where pos and len are of type int).

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string x= "Be positive and Keep Smiling";
    string y;
    y=x.substr(16,12);
    cout<<y;
    return 0;
}

Assigning  one string to another string in c++.

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
char s[]="Bepositive,keep smiling";
char word[20];
char w[20];
int i,j=0;
string s1="Shining star";
string s2="tit for tat";
s1=s2;
cout<<s1<<endl;
for(i=0;s[i]!=' ';i++)
{  word[i]=s[i];
}
cout<< "the string word is"<<word<<endl;
for(s[i]==' ';s[i]!='';i++)
{
w[j]=s[i+1];
}
cout<<"the string w is " <<w<<endl;
   /* w[20]=s[20];
    cout<<"direct assigning value"<<word<<endl;*/
    getch();
    return 0;
}

Searching for (and Finding) Patterns in Strings.

Searching  or finding for a string ,or  a character in a given string means you already have a string which have certain characters in it,in that particular string you need to find the occurance of another string i.e what is the location of  second string in first string.

For ex:

string x=”how are You”;

string y =”You”;


 

 

 

 

 

Here  x is a string object, and we wants  to search for a string y in x.to do so we need to write:

 

 

 

Here startLoc is a variable of int type where the index of x string will be saved from where y string starts.

As string y in string s starts from index s[8] ,the value of startloc will be 8.

This method returns the starting index of the leftmost occurrence of y in x, if any occurrence exits; otherwise, the method returns the length of x.

We can also find a location of a character in a given string by giving our own position to start from:for example

To search starting from a position pos, do:

 

 

Using the same given Index:

int startloc =x.find(y,4);

It  means occurrence of y string will be checked from Index x[4];

NOTE THAT

In all the versions of find , the argument y can be a string object, a C-style string variable, double-quoted string, a char variable, or a single-quoted char.



The comparison of all the C++ String  operations we did now with the c library Functions



String manipulating functions/Objects

String manipulating function in C++ means those functions which could  make a change or modify   a given string,rather than creating any other string .

Modify String functions are:

1.insert()

2.replace()

3.erase()

4.append()

1.insert():

Suppose x is a string object, and let y be another string to be inserted at position pos of the string of x

To insert y, do:

The argument y can be: a string object, a C-style string variable, or a double-quoted string.


for example:

string x=”Cool Friends”;

string y=”Best “;


In given example x and y string objects are initialized with values Cool Friends and Best respectively.I need to insert string object y in x.to do so we need to use function

 

 

 

 

 

 

 

 

 

#include<iostream>
using namespace std;
int main()
{
    string x= "Cool Friends";
    string y="Best ";
    x.insert(5,y);
    cout<<x<<endl;
    y.insert(5,"family");
    cout<<y<<endl;
    return 0;
}

2)replace()

Replace as the name tells,we will modify the parent string object by replacing the characters of  the parent string with another string.Using the same example:


for example:

string x=”Cool Friends”;

string y=”Best “;


Here i need to replace Friends with string s2 i.e cool. for this i need to mention 3 arguments in replace string object.

1.Position : at which position s2 is to be inserted.

2.length:length means number of characters of string x needs to be replaced. Its basically(pos+len),where pos is 0(Zero).

3.String name:string with which the characters are replaced.

To do so you need :

 

 

Since i need to replace characters of x from index 5 and total no.of characters to be replaced  by string y is  7.

we can also replace by directly giving the string in arguments.as

 

 

 


AFTER THE REPLACE FUNCTION :

STRING X , BECOMES  Cool Best


#include<iostream>
using namespace std;
int main()
{
x= "Cool Friends";
string y="Best ";
x.replace(5,7,y);
cout<<x;
return 0;
}

3)erase()

erace() string function is used to erace characters from a parent string.Its similar to replace function,but here characters are not replaced  perhaps we delete them..

For doing so it needs 2 arguments:

Position: From which position(Index) you need to erase/delete characters

length: length means how many characters to need to delete from a given position.

 

 


for example:

string x=”Cool Friends”;


Taking the same example,i need to delete friends from string x.for doing so  we need to mention the index from where i need to erase characters and length i.e how many characters to be erased.

 

 

The x string becomes:Cool

Friends are erased from string s by using erase function.

If i need to erase complete string i can directly write

x.erase();

for the same we can also use clear() function.

x.clear();

It is also same as x.erase(), will delete the whole strings,leaving no characters in it(null string).

#include<iostream>
using namespace std;
int main()
{
string x= "Cool Friends";
x.erase(5,7);
cout<<x<<endl;
x.erase();
cout<<x;
return 0;
}

A compiled program of string manipulating function in a single program:

#include<iostream>
using namespace std;
int main()
{
    string x= "high";
    string y="";
    int len;
    bool check;
    len = x.length();// Length of the String
    cout<<"Length of the string is: "<<len<<endl;
    len = x.size();
    cout<<"Length of the string is: "<<len<<endl;
    check = y.empty();//returns 1 if empty 0 if non Empty
    cout<<"Boolean Value is: "<<check<<endl;
    // Sub String
    string substr = x.substr(1,3);
    cout<<"Substring is: "<<substr<<endl;
    //String Insert: Insert string in the specified location of the string
    string strins = " end";
    y = x.insert(4,strins);
    cout <<"after inserting  value of y becomes  "<<y<<endl;
    //Replace the string;
    //Replaces the string from specified position to specified pos
    string z = "hello";
    y = x.replace(1,2,z);
    cout <<"Replace function :   "<<y<<endl;
    // To erase or clear a string
      z = x.erase(0,2);
    cout<<"after erased values: "<<z<<endl;
    cout<<"Before clear values: "<<x<<endl;
    x.clear();
    cout<<"after clear values: "<<x<<endl;
    //find finds the leftmost occurence of the string
    x = "helloworld";
    int startLoc = x.find("r",4);
    cout<<"No of times String appears: "<<startLoc<<endl;
        //rfind finds the rightmost occurence of the string
    x = "helloworld";

}

Sorting of string

#include<iostream>
#include<string.h>
using namespace std;
main()
{char str[5][10], t[20];
int i, j;
    cout<<"Enter any five string (name) : ";
    for(i=0; i<5; i++)
    {
        cin>>str[i];
    }
    for(i=0; i<5; i++)
    {for(j=1; j<5; j++)
        {if(strcmp(str[j-1], str[j])>0)
            {
                strcpy(t, str[j-1]);
                strcpy(str[j-1], str[j]);
                strcpy(str[j], t);
            }
        }
    }
    cout<<"Strings (Names) in alphabetical order : n";
    for(i=0; i<5; i++)
    {
        cout<<str[i]<<"n";
    }
}

Leave a Comment