ujjal1's blog

By ujjal1, 15 months ago, In English

Note on string(STL)

By Ujjal Roy

string

In C++, the Standard Template Library (STL) is a powerful library that provides a collection of template classes and functions to work with common data structures and algorithms. One of the fundamental components of the STL is the string class, which is used for working with strings of characters.

Declaration and initialization

The syntax of declaration and initialization of string below,


string name; string s;//Initializing an empty string string s1="Hello ujjal";//Initializing with a string literal

Accessing individual characters using the [] operator or at() method. It is possible to change element of string by [] this operator ,here the example

cout<<s1[0]<<" "<<s1[1]<<endl;
s1[0]='A';
s1[1]='B';
cout<<s1<<endl; //output : ABllo ujjal

String Append/Concatenation

By append() function we can concatenate two string. It takes a string as a parameter and return a new string. time complexity of Append() in string is O(n)

string s="Ujjal";
string s1="Roy";
string s3=s.append(s1);
cout<<s3<<endl;

instead of append() function The ‘+’ operator can be used to add strings together to make a new string. The character concatenation and string concatenation are the same process.

 s="Ujjal";
s1="Roy";
s=s+' ';//"Ujjal ";
s+=s1;// "Ujjal Roy";
cout<<s<<endl;

size()/length()

the size() function return the size of the string. Also the length() function provide the total size of string. The time complexity of both function is constant time O(1).

string s="Hello HSTU";
cout<<s.size()<<endl;//output :10
cout<<s.length()<<endl;//output :10

string traversing

Traversing a string can be done using a variety of methods, similar to other sequential containers like arrays or vectors. Here are a few common approaches for traversing a for loop,while loop,do while loop,Iterator, For-each loop.

**Using for loop**
 string s="Hello";
for(int i=0;i<s.size();i++)
{
cout<<s[i]<<" ";
} // output : H e l l o

Using For-each loop

for(auto it:s)cout<<it<<" ";// output: H e l l o

clear()

clear() is a member function of the string class in the Standard Template Library. It takes no parameters and it returns a string with zero characters (an empty string). The time complexity of the clear() function of the string class in C++ STL is O(1) in most cases.

string name="Hello coders";
name.clear();
cout<<name.size()<<endl;//output: 0
cout<<name<<endl;// output :

reverse()

reverse() function used for reverse a string. We need to provide the beginning and ending iterators of the string. This reverses the characters within the string, effectively reversing the entire string. The time complexity of the std::reverse() function in C++ STL is O(N),

string s="Ujjal";
reverse(s.begin(),s.end());
cout<<s<<endl; //output : lajjU

empty()

this is Boolean function Returns whether the string is empty if it is empty return true (1) otherwise false. the time complexity of this function is O (1).

string s="HSTU";
cout<<s.empty()<<endl;//output : 0
s.clear();
cout<<s.empty()<<endl;//output : 1

find()

Searches the string for the first occurrence of the sequence specified by its arguments. It return The position of the first character of the first match. If no matches were found, the function returns string::npos. The time complexity of find is O(n)

string s="Hello world";
cout<<s.find("ello")<<endl;
if(s.find("Hello")!=string::npos)cout<<"YES\n";
else cout<<"NO\n";
//output: 1
// YES

compare of two string

we can compare two strings using various methods depending on the specific comparison you want to perform. All the comparisons in O(N) times. We can use == operator for compare two string

string s1,s2;
s1="Ujjal";
s2="Ujjal";
if(s1==s2)cout<<"equal\n";
else cout<<"Not equal\n";
// output : equal

compare () is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. Compare () returns an integer value rather than a Boolean value. Return 0 if both string are equal Return less than zero<0 if parameter string is greater Otherwise return greater than zero>0.

1. string s1,s2;
2. s1="Ujjal";
3. s2="Roy";
4. if(s1.compare(s2)<0)cout<<"s1 is less than s2\n";
5. else cout<<"s2 is less than s1\n";

Transform()

Here is the code for transform all character to lower case and upper case.

string s1="Ujjal";
string s2="Roy";
transform(s1.begin(),s1.end(),s1.begin(),::tolower);
cout<<s1<<endl;// output : ujjal
transform(s2.begin(),s2.end(),s2.begin(),::toupper);
cout<<s2<<endl;//output : ROY

User input of string

It is possible to use the extraction operator >> on cin to store a string entered by a user. cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can only store a single word.

string s;
cin>>s;
cout<<s<<endl;
input: Hello
output: Hello

for taking a line of input we can use getline it take two parameter as a input first cin and second string variable.

string s;
getline(cin,s);
cout<<s<<endl;
input : hello world.
Output: hello world.

After using cin to read data, there might be leftover newline characters or other formatting characters in the input buffer. This can lead to unexpected behavior when using getline subsequently. For solve this problem we use cin.ignore();

 int n;
string s;
cin>>n;
cin.ignore();
getline(cin,s);
cout<<s<<endl;
input: 
5
Hello World
Output: Hello World

erase()

erase() function erase the single element or a specific rang. It return an iterator referring to the character that now occupies the position of the first character erased, or end() if no such character exists. Time complexity of this function O(n).

string s="Hello ujjal";
s.erase();//Erase all character
cout<<s<<endl;//output : 
s="Hello";
s.erase(2);//erase all element from poition 2(ZERO base index).
cout<<s<<endl; //output : He
s="Hello, Ujjal";
s.erase(2,4);//From index 2 and erase 4 characters(zero base)
cout<<s<<endl; //output : He Ujjal
s="Hello, Ujjal";
s.erase(s.begin()+5);// Erase the single character at iterator s.begin()+5
cout<<s<<endl;//output : Hello Ujjal
s="Hello, Ujjal";
s.erase(s.begin(),s.begin()+4);//erase the elements from begin() to 
before begin()+4
cout<<s<<endl;// output: o, Ujjal
 
string s="Hello, coders";
s.erase(remove(s.begin(),s.end(),'o'),s.end());//erase all 'o' from s
cout<<s<<endl;// output : Hell, cders

Sorting of string

sort() is a built-in function in C++'s Standard Template Library. The function takes in a beginning iterator, an ending iterator, and (by default) sorts the iterable in ascending order. The function can also be used for custom sorting by passing greater comparator function or reverse iterator. Time complexity of this function is O(NlogN).

Sort by ascending order

string s ="Ujjal";
sort(s.begin(),s.end());
cout<<s<<endl;//output : Uajjl

sort by descending order

string s ="Ujjal";
sort(s.rbegin(),s.rend());
cout<<s<<endl;//output : ljjaU

Full text and comments »

  • Vote: I like it
  • -23
  • Vote: I do not like it

By ujjal1, 15 months ago, In English

Note on Vector(STL)

By UJJAL ROY

1.1 Vector

Vector is a dynamic array/Resizable Array. We can push or pop element at any time That means we can increase or decrease the size of the vector. It not necessary to tell size of the vector when it is declared.

Declaration of vector

vector<type> name;

Here the type can be anything like int, char, string, double etc.

 vector<int>v;

vector<string>vs;

vector<char>vc;

vector<vector<char>>vv;

It is allowed to tell size of the vector at the declaration time. Initially all the vector element will be initialized by zero or we can be initialized by any value at the time of declaration

 vector<int>v(5); //{0,0,0,0,0}
vector<int>v(5,10); //{10,10,10,10,10

Initialization

vector<int> v = {10, 20, 15, 50};
vector<string> vs = {"Hello","Ujjal"};

Now we can use it like as array. We can access any index like as array

cout<<v[0]<<endl;//output : 10
v[1]=100;
cout<<v[1]<<endl; //output : 100

vector traversing

we can use for loop, while loop, do while loop or For-each loop for traversing vector.

Using for loop

 vector<int> v = {10, 20, 15, 50};
for (int i = 0; i < 4; i++)
{
cout << v[i] << endl;

}

Using For-each loop

 vector<int> v = {10, 20, 15, 50};
for (auto u : v)
{
cout << u << endl;
}
**Output :**
 10
 20
 15
 50

push_back()

For adding an element of a vector in the end we can use push_back() function. The complexity of this function is O(1).

 vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for (int i = 0; i < 3; i++)
{
cout << v[i] << " ";
}
 vector<char> vs; // char type vector
vs.push_back('U');
vs.push_back('J');
vs.push_back('J');
vs.push_back('A');
vs.push_back('L');
for (auto u : vs)
cout << u;

For taking input from user. we will use extra variable of same type. Firstly, we will take input in this variable then we will push it on the vector.

 vector<double> vd;
for (int i = 0; i < 5; i++)
{
double r;
cin >> r;
vd.push_back(r);
}

size()

The size() function directly return the size of vector. The time complexity of this function O(1).

 vector<int>v={10,20,30,40};
cout<<v.size()<<endl; // Output : 4.

clear()

clear() remove all the element from the vector. So the vector will be empty. Its time complexity is O(1).

vector<int>v={10,20,30,40};
cout<<v.size()<<endl; // Output : 4.
v.clear();
cout<<v.size()<<endl; //output: 0

empty()

empty() is a Boolean function it return 1(True) when vector is empty otherwise it return 0(false). Its time complexity is O(1).

vector<char>vc={'A','B'};
cout<<vc.empty()<<endl; //output : 0
vc.clear();
cout<<vc.empty()<<endl; //output : 1

insert()

for adding new element at any index we use insert() function. It take two parameter one is iterator (mainly it is position) and another is the value of this element.

For example the vector is v={1,2,3,4}

v.insert(v.begin()+1,10);

here v.begin()+1 indicate index v[1]. so the value of index v[1]=10 and all the

element will be shift to the next position that means previously 2 was at v[1] index

now it will be v[2] index 3 will be v[3] and so on.

Now we thing the complexity of this function. Here for begin() iterator all the element will be shift so the complexity of this function is O(n).

then v will be v={1,10,2,3,4}

vector<int>v={1,2,3,4};
v.insert(v.begin()+1,10);//{1,10,2,3,4};
for(auto u:v)cout<<u<<" "; //output : 1 10 2 3 4

erase()

this function almost similar with insert function but insert() add new element to the vector and erase() remove element from vector .

 vector<int>v={1,2,3,4,5};
v.erase(v.begin()); //2,3,4,5
for(auto u:v)cout<<u<<" ";
cout<<endl;
v.erase(v.begin(),v.begin()+2);//{4,5}; 
for(auto u:v)cout<<u<<" ";

resize()

this function changes the size of vector and rest of the element are assign by zero. The Time Complexity comes out to be O(n).

vector<int>v(5,2);
cout<<v.size()<<endl; //output:5
for(int i=0;i<v.size();i++)cout<<v[i]<<" "; //output :{2,2,2,2,2};
v.resize(10);
cout<<v.size()<<endl; //output:10
for(int i=0;i<v.size();i++)cout<<v[i]<<" ";//output 
:{2,2,2,2,2,0,0,0,0,0};

reverse()

this function reverse the whole vector. The syntax of the function. The time complexity is O(n).

ector<int>v={1,2,3,4}
reverse(v.begin(),v.end());
now v={4,3,2,1}

front() and back()

front() function return the first element of vector and back() function the last element o this vector. The time complexity of both function is O(1).

vector<long long int>v={10,20,30,40,50};
cout<<v.front()<<" "<<v.back()<<endl; //output 10 50

max_element() and min_element()

this function return the first iterator of maximum element .and the complexity of this function is O(n).

vector<int>v={1,2,3,5,4,1,5};
auto it=max_element(v.begin(),v.end());
cout<<*it<<endl;// output : 5. value of maximum element
cout<<it-v.begin()<<endl; //output : 3. Index of maximum element

the use of min_element() is similar to max_element() function.

Copy of vector

Vector can be copy directly like as primitive variable. When we copy a vector source vector will remain unchanged


vector<char>vc={'U','j','j','a','l'}; vector<char>vc1; vc1=vc; for(auto u:vc1)cout<<u; //output:Ujjal

sorting of vector

using sort() function vector can be sort. This is ascending order by default. Using greater comparator it will be descending order or we can use rbeging, rend Iterators

code for ascending order

vector<int>v={4,1,2,3,2,5,1};
sort(v.begin(),v.end());
for(auto u:v)cout<<u<<" ";
// output : 1 1 2 2 3 4 5

Code for descending order

 vector<int>v={4,1,2,3,2,5,1};
sort(v.begin(),v.end(),greater<int>());//sort(v.rbegin(),v.rend());
 for(auto u:v)cout<<u<<" ";
// output : 5 4 3 2 2 1 1

Full text and comments »

  • Vote: I like it
  • -2
  • Vote: I do not like it