Welcome to the Data Structures Basics series. Its time for our third data structure i.e Strings.
What is a String?
Strings are to characters what arrays are to other data types. This doesn't mean that you cannot make an array of characters. You can, and it is so common that there is a different data type for it, which is known as Strings. A string is an array of characters. It is one of the most common and regularly used Data Structure. Not only that, Strings have an edge over a character array in some ways. What are they? Let's see
Strings vs Character Arrays.
- Built in functions like substring(), charAt() etc can be used on Strings.
- Strings can be stored in any any manner in the memory.
- ‘+’ can be used to appended strings together to form a new string.
Syntax and In-Built functions
It is very easy to create a string. Strings possess a lot of in-built functions that are very handy to use. For example:
string s = "hashnode"; // creates a string s.
s.substr(0,3); // gives a substring starting at index 0 of size 3.
s.find("hash"); // finds the first occurence of "hash" in s. If not found, returns -1 or else returns the index.
s.compare("hasn"); // compares "hasn" with s. returns 0 if same. 1 if s is lexograhically bigger and -1 if smaller.
s.copy(s2); // copies the content of s to a new character array called s2.
s.clear(); // clears the content of the string
s.empty(); // returns a true if string is empty and false if not.
There are a lot more functions but these were some which are used more frequently than others.
Time Complexities of a String.
Strings are similar to arrays and hence their time complexities are also very similar. The time complexities for the 4 major operations, i.e insert, delete, search, access and the inbuilt functions discussed above are as follows. **- Search: O(N)
- Insert: O(N)
- Delete: O(N)
- Access: O(1)
- Iterate; O(N)
- Compare: O(M+N)
- Clear Function: O(N)
- Copy Function: O(N)
- Find Function: O(N)
- Substr function: O(Length of the Substring)**
Code Example.
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "hashnode";
char s2[10];
string s3 = s.substr(0,3); // gives a substring starting at index 0 of size 3.
int idx = s.find("hash"); // finds the first occurence of "hash" in s. If not found, returns -1 or else returns the index.
int num = s.compare("hasn"); // compares "hasn" with s. returns 0 if same. 1 if s is lexograhically bigger and -1 if smaller.
s.copy(s2,s.size()); // copies the content of s to a char array called s2.
s.clear(); // clears the content of the string
bool x = s.empty(); // returns a true if string is empty and false if not.
}
Conclusion
- So, this wraps up the article on Strings and its basics.
- You now have enough knowledge of strings to go and start experimenting with them on your IDE.
- Next up we will learn about Stacks