String Data Structure

This comprehensive guide to Strings Data Structures covers the basics, how to get started, learning techniques, strategies, resources, and common problems to help you effectively understand and use strings in programming.

Overveiw

Chapters

3 Chapter are there in this module reguarding string data structures.

Start Learning

Quiz

Quiz on the topics being learnt in this module to ensure your knowldege.

Take Quiz

Problems

Practice Problems on the topics being covered in this module

See Problems

What is String – Definition & Meaning

In Data Structures and Algorithms (DSA), a String can also be defined as a sequence of characters, stored in contiguous memory locations, terminated by a special character called the null character ‘\0’.

String

Characteristics of String:

  • Ordered: Strings are ordered sequences of characters, where each character has a unique position in the string.
  • Indexable: Strings can be indexed, meaning that individual characters within a string can be accessed using a numerical index.
  • Comparable: Strings can be compared to each other to determine their relative order or equality.

Basic String Operations with Implementation

In this post, we will look into some of the basic String operations such as:

Accessing characters by index in a string.

            
// CPP code for accessing an element by index
#include <iostream>
#include <string>

using namespace std;

// Function to demonstrate access by index
char accessCharByIndex(string str, int k)
{
    // return the character at Kth index in the string str
    return str[k];
}

// Driver code
int main()
{
    string str("GeeksforGeeks ");
    int k = 4;
    cout << accessCharByIndex(str, k) << endl;
    return 0;
}
            
        

Output:

            
                s
            
        



Inserting Character/String into a String.

            
// CPP code for inserting character/string into a String
#include <iostream>
#include <string>

using namespace std;

// Function to demonstrate insert
void insertDemo(string str, string ch, int k)
{
    // Inserts ch at kth index of str
    str.insert(k, ch);
    cout << "Modified String : " << str << endl;
}

// Driver code
int main()
{
    string str("GeeksGeeks ");
    string ch = "for";
    int k = 5;

    cout << "Original String : " << str << endl;
    insertDemo(str, ch, k);

    return 0;
}
            
        

Output:

            
                Original String : GeeksGeeks 
                Modified String : GeeksforGeeks 
            
        



Modifying character in String.

          
// CPP code for modifying character in a String
#include <iostream>
#include <string>

int main()
{
    // Get the string
    std::string str = "Geeks Gor Geeks";

    // Get the index
    int index = 6;

    // Get the character
    char ch = 'F';

    // Print the original string
    std::cout << "Original String = " << str << std::endl;

    str.replace(index, 1, 1, ch);

    // Print the modified string
    std::cout << "Modified String = " << str << std::endl;

    return 0;
}
          
      

Output:

          
              Original String = Geeks Gor Geeks
              Modified String = Geeks For Geeks
          
      



Deletion of character in String.

        
// C++ program to remove a particular character
// from a string.
#include <bits/stdc++.h>
using namespace std;

void removeChar(char* s, char c)
{
    int j, n = strlen(s);
    for (int i = j = 0; i < n; i++)
        if (s[i] != c)
            s[j++] = s[i];

    s[j] = '\0';
}

int main()
{
    char s[] = "geeksforgeeks";
    removeChar(s, 'g');
    cout << s;
    return 0;
}
        
    

Output:

        
            eeksforeeks
        
    



Concatenating strings (combining multiple strings into one).

        
// C++ Program for string concatenation using '+' operator
#include <iostream>
using namespace std;

int main()
{
    string init("this is init");
    string add(" added now");

    // Appending the string.
    init = init + add;

    cout << init << endl;
    return 0;
}
        
    

Output:

        
            this is init added now
        
    



Finding the length/size of a string.

        
// C++ program to find length of a string
#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    // String obj
    string str = "GeeksforGeeks";

    // size of string object using size() method
    cout << str.size() << endl;

    return 0;
}
        
    

Output:

        
            13
        
    



Comparing Strings for Equality.

      
// C++ code for comparing strings for equality
#include <iostream>
using namespace std;

bool stringCompare(const string& str1, const string& str2)
{
    int l1 = str1.length();
    int l2 = str2.length();
    int lmin = min(l1, l2);

    for (int i = 0; i < lmin; i++)
    {
        int str1_ch = static_cast<int>(str1[i]);
        int str2_ch = static_cast<int>(str2[i]);

        if (str1_ch != str2_ch)
        {
            return false;
        }
    }

    if (l1 != l2)
    {
        return false;
    }
    else
    {
        return true;
    }
}

int main()
{
    string string1 = "Geeksforgeeks";
    string string2 = "Practice";
    string string3 = "Geeks";
    string string4 = "Geeks";

    cout << "Comparing " << string1 << " and " << string2 << " : " 
          << stringCompare(string1, string2) << endl;
    cout << "Comparing " << string3 << " and " << string4 << " : " 
          << stringCompare(string3, string4) << endl;
    cout << "Comparing " << string1 << " and " << string4 << " : " 
          << stringCompare(string1, string4) << endl;

    return 0;
}
      
  

Output:

      
          Comparing Geeksforgeeks and Practice : 0
          Comparing Geeks and Geeks : 1
          Comparing Geeksforgeeks and Geeks : 0
      
  

Iterate over characters of a string

Given a string str of length N, the task is to traverse the string and print all the characters of the given string.



Naive Approach: The simplest approach to solve this problem is to iterate a loop over the range [0, N – 1], where N denotes the length of the string, using variable i and print the value of str[i].

// C++ program to implement 
// the above approach 

#include <bits/stdc++.h> 
using namespace std; 

// Function to traverse the string and 
// print the characters of the string 
void TraverseString(string &str, int N) 
{  
  // Traverse the string 
  for (int i = 0; i < N; i++) { 

      // Print current character 
      cout<< str[i]<< " "; 
  } 

} 

// Driver Code 
int main() 
{ 
  string str = "GeeksforGeeks"; 

  // Stores length of the string 
  int N = str.length(); 

  TraverseString(str, N); 
}

Output:

G e e k s f o r G e e k s

Time Complexity: O(N)
Auxiliary Space: O(1)




Auto keyword – based Approach: The string can be traversed using auto iterator.

// C++ program to implement 
// the above approach 

#include <bits/stdc++.h> 
using namespace std; 

// Function to traverse the string and 
// print the elements of the string 
void TraverseString(string &str, int N) 
{ 
  // Traverse the string 
  for (auto &ch : str) { 

      // Print current character 
      cout<< ch<< " "; 
  } 
} 
// Driver Code 
int main() 
{ 
  string str = "GeeksforGeeks"; 

  // Stores length of the string 
  int N = str.length(); 

  TraverseString(str, N); 
}

Output:

G e e k s f o r G e e k s

Time Complexity: O(N)
Auxiliary Space: O(1)




Iterator – based Approach: The string can be traversed using iterator.

// C++ program to implement 
// the above approach 

#include <bits/stdc++.h> 
using namespace std; 

// Function to traverse the string and 
// print the elements of the string 
void TraverseString(string &str, int N) 
{ 

  // Stores address of  
  // a character of str 
  string:: iterator it; 

  // Traverse the string 
  for (it = str.begin(); it != str.end(); 
                                 it++) { 
      // Print current character 
      cout<< *it<< " "; 
  } 
} 

// Driver Code 
int main() 
{ 
  string str = "GeeksforGeeks"; 


  // Stores length of the string 
  int N = str.length(); 
  TraverseString(str, N); 
}

Output:

G e e k s f o r G e e k s

Time Complexity: O(N)
Auxiliary Space: O(1)