Basics of String in C++

String in C++

Basic Implementation & Syntax


The below code leads to the basic syntax in creating and accepting user input for a string. Note that we are using the 'getline()' function and not the conventional 'cin' to accept user input.

The reason for this is that 'cin' will accept the string up till it encounters a 'space' after which the string will be terminated to the input.

The getline() function however accepts the entire line as an input, including the space.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    //declaring a string variable
    string sample;
    
    //accepting a string
    getline(cin,sample);
    
    //storing charecters in vector
    vector<char> partofsample;
    
    //vectors basic concepts
    //Explained in another shorts
    for(int i=0;i<sample.length();i++)
    {
        partofsample.push_back(sample[i]);
    }
    
    //printing and checking
    cout<<endl<<sample;
    cout<<endl;
    for(int i=0;i<partofsample.size();i++)
    {
        cout<<partofsample[i]<<" ";
    }
}


Here is a sample output for your checking and understanding.


Now in this code, you can see apart from a normal output, we have used vectors.
The basic vector concept was taught in another shorts video & blog, so check it if
you need a prior understanding of the syntax.

    //vectors basic concepts
    //Explained in another shorts
    for(int i=0;i<sample.length();i++)
    {
        partofsample.push_back(sample[i]);
    }
    
    //printing and checking
    cout<<endl<<sample;
    cout<<endl;
    for(int i=0;i<partofsample.size();i++)
    {
        cout<<partofsample[i]<<" ";
    }

Here, we are storing each and every element of the string in a vector(including space).

Below is the code to search for a given character in a string, & how many times it
occurs during the string iteration.

#include<bits/stdc++.h>
using namespace std;
int main()
{
    string sample;
    getline(cin,sample);
    vector<char> partofsample;
    char checkfor;
    cin>>checkfor;
    
    //count the number of times letter occurs
    int cnt=0;
    for(int i=0;i<sample.length();i++)
    {
        if(sample[i]==checkfor)
            cnt++;
        partofsample.push_back(sample[i]);
    }
    
    //printing
    cout<<endl<<sample;
    cout<<endl;
    for(int i=0;i<partofsample.size();i++)
    {
        cout<<partofsample[i]<<" ";
    }
    cout<<endl<<cnt;
}

Here is a sample output.


This is the basic syntax and implementation for strings. You can try other string
manipulations such as :-
    1. Convert uppercase to lowercase and vice-versa.
    2. Find number of vowels.
    3. Find palindrome strings.

If this helps you, consider subscribing our YouTube channel to motivate us
to help you more :)

Comments