×

String Operations in Data Structures

Operations on Strings

  • Reversing the order of words in a sentence

Reversing a string is a technique that reverses or alters the order of a given string so that the last character becomes the first character, and so on. We may also test the Palindrome of a given string by reversing the original string.

For instance, we may type "JAVATPOINT" and then use the reverse procedure. The reverse algorithm returns "TNIOPTAVAJ," which is the inverse of the original string.

REVERSING A STRING

Operations on Strings

In C, there are several methods for finding the inverse of a string.

  1. The strrev() method is used to reverse a string.
  2. Without using the library function, reverse a string
  3. Using a for loop, reverse a string
  4. Using a while loop, reverse a string

1. The strrev() method is used to reverse a string.

#include <stdio.h>  
#include <string.h>  
int main()  
{  
    char reverse_string[40]; // declare the length of the character string
    printf (" \n Type a string to be reversed: ");  
    scanf ("%s", reverse_string);  
          
    // To reverse a string, use the strrev() method.
    printf (" \n Following is the string's reversal: %s ", strrev(reverse_string));  
    return 0;  
}  

The following output should be generated by this programme:

Output

Type a string to be reversed: JAVATPOINT
Following is the string's reversal: TNIOPTAVAJ

2. Without using the library function, reverse a string

#include <stdio.h>  
#include <string.h>  
      
// stringreverse() function definition
void stringreverse(char *reverse_string)  
{  
    // variable declaration
    int i, len, temp;  
    len = strlen(reverse_string); // To get the length of the reverse string string, use strlen().
          
    // To iterate the string, use a for loop.
    for (i = 0; i < len/2; i++)  
    {  
        // The temp variable is used to temporarily store the string.           	temp = reverse_string[i];  
        reverse_string [i] = reverse_string [len - i - 1];  
        reverse_string [len - i - 1] = temp;  
    }  
}  
          
int main()  
{  
    char reverse_string [50]; // char string length  
    printf (" Enter the following string: ");  
    gets(reverse_string); // To take a string, use the gets() method.
          
    printf (" \n Before you reverse the string:%s \n", reverse_string);  
              
    // use the stringreverse () function
    stringreverse (reverse_string);  
    printf (" After reversing the string: %s", reverse_string);  
}

The following output should be generated by this programme:

Output

Enter the following string: Welcome to JavaTPoint


Before you reverse the string: Welcome to JavaTPoint
After reversing the string: tnioPTavaJ ot emocleW

3. Using a for loop, reverse a string.

#include <stdio.h>  
#include <conio.h>  
#include <string.h>  
void main()  
{  
	char reverse_string[50], temp; // set the size of the reverse_string[] array	
	int i, left, right, len;  
	printf (" \n Show a reverse string in C:\n");  
	printf (" ----------------------- ");  
	printf (" \n Enter the following string to reverse the order:");  
	scanf( "%s", &reverse_string);  
	len = strlen(reverse_string); // get the string's length
	left = 0; // set the left index to 0
	right = len - 1; // set the correct index len - 1
	// To save the reverse string, use a for loop.  
	for (i = left; i <right; i++)  
	{  
		temp = reverse_string[i];  
		reverse_string[i] = reverse_string[right];  
		reverse_string[right] = temp;  
		right--;  
	}  
	printf ("The original string's inverse is: %s ", reverse_string);  
	getch();  
}

The following output should be generated by this programme:

Output

Show a reverse string in C:
 -----------------------
Enter the following string to reverse the order: JAVATPOINT
The original string's inverse is: TNIOPTAVAJ

4. Using a while loop, reverse a string.

#include <stdio.h>  
#include <string.h>  
int main()  
{  
	char reverse_string[50], temp; // declare and initialise the string array's size
	int i = 0, j =0;  
	printf ("Enter the following string to be reversed: ");  
	scanf( "%s", reverse_string);  
	j = strlen (reverse_string) - 1;  // get the string's length  


	// To specify the condition, use a while loop.	
	while ( i < j)   
	{  
		// use a temp variable to hold the reverse_string characters  
		temp = reverse_string[j];  
		reverse_string[j] = reverse_string[i];  
		reverse_string[i] = temp;  
		i++; // i increased by one
		j--; // j is reduced by one
	}  
	printf ("The string in reverse: %s", reverse_string);  
	return 0;  
}

The following output should be generated by this programme:

Output

Enter the following string to be reversed: JAVATPOINT
The string in reverse: TNIOPTAVAJ
  • To duplicate one string to another
#include <stdio.h>
#include <string.h>
#include <stdlib.h>




void main()
{
    char string_1[100], string_2[100];
    int  i;


       printf("\n\n Copy one string and paste it into another.:\n");
       printf("-----------------------------------------\n"); 	
       printf("Enter the string here.: ");
       fgets(string_1, sizeof(string_1), stdin);
	   
    /* string1 to string2 is copied character by character. */
    i=0;
    while(string_1[i]!='\0')
    {
        string_2[i] = string_1[i];
        i++;
    }


    // Ensures that the string is finished with a NULL.
    string_2[i] = '\0';


    printf("\nThe Initial string is : %s\n", string_1);
    printf("The Copied string is : %s\n", string_2);
    printf("Number of characters copied : %d\n\n", i);
}

The following output should be generated by this programme:

Output

Copy one string and paste it into another.:                                                                         
-----------------------------------------                                                                     
Enter the string here.: Greetings from JavaTPoint.                                                             
                                                                                                              
The Initial string is : Greetings from JavaTPoint.                                                          
                                                                                                              
The Copied string is : Greetings from JavaTPoint.                                                         
                                                                                                              
Number of characters copied : 26
  • Detecting a palindrome

A palindrome number is one that is the same after being reversed. Palindrome numbers include 171, 14641, 838, 9123219, and 48984.

Algorithm for palindrome numbers

  • Obtain the number from the user
  • Keep the value in a temporary variable.
  • Reverse the digits
  • Compare the temporary and reversed numbers.
  • If the numbers are the same, print a palindrome.
  • Otherwise, print a number that is not a palindrome.

C programme for palindromes

#include <stdio.h>  
#include <conio.h>  
#include <string.h>  
void main()  
{  
	char reverse_string[50], temp; // set the size of the reverse_string[] array	
	int i, left, right, len;  
	printf (" \n Show a reverse string in C:\n");  
	printf (" ----------------------- ");  
	printf (" \n Enter the following string to reverse the order:");  
	scanf( "%s", &reverse_string);  
	len = strlen(reverse_string); // get the string's length
	left = 0; // set the left index to 0
	right = len - 1; // set the correct index len - 1
	// To save the reverse string, use a for loop.  
	for (i = left; i <right; i++)  
	{  
		temp = reverse_string[i];  
		reverse_string[i] = reverse_string[right];  
		reverse_string[right] = temp;  
		right--;  
	}  
	printf ("The original string's inverse is: %s ", reverse_string);  
	getch();  
} 

The following output should be generated by this programme:

Output

Show a reverse string in C:
 -----------------------
Enter the following string to reverse the order: JAVATPOINT
The original string's inverse is: TNIOPTAVAJ
  • Counting the number of words in a string

In this programme, we must count the words in the string.

As an example:

Hello and welcome to JavaTpoint! We hope we were able to provide you with what you were searching for.

There are a total of 19 words in the string.

Counting the total amount of words in a string algorithm

  • Create a string.
  • We'll loop through the string and count the spaces to see how many words there are. Because each word is always followed by a space.
  • If a string begins with a space, the initial space should not be counted because it is not preceded by a word.
  • We'll add one to the total to count the last word.

C programme for Counting the total amount of words in a string

#include <stdio.h>  
#include <string.h>  
   
int main()  
{  
	char sentence_string[] = "Hello and welcome to JavaTpoint! We hope we were able to provide you with what you were searching for.";  
	int wordCount = 0;  
  
	for(int i = 0; i < strlen(sentence_string)-1; i++) {  
		// Counts the number of gaps in the string.  
		// It excludes the initial space since it is not considered a word.
		if(sentence_string[i] == ' ' && isalpha(sentence_string[i+1]) && (i > 0)) {  
			wordCount++;  
		}  
	}
	// Increase wordCount by 1 to count the last word in the string.	wordCount++;  
  
	// The total number of words in the provided string is shown.
	printf("The total number of words in the string is: %d", wordCount);  
   
	return 0;  
} 

The following output should be generated by this programme:

Output

The total number of words in the string is: 19
  • Determining the number of repeated words within a string

We need to locate and display the duplicate words in the string in this software.

big black bug bit a big black dog on his big black nose  

We initially break the string into words in order to locate the duplicate words. We count how many times each word appears in the string. If the count is larger than one, the string contains a duplicate word.

Algorithm for number of repeated words within a string

  • Create a string.
  • To make the comparison insensitive, convert the string to lowercase.
  • Make a word out of the string.
  • To discover duplicate words, two loops will be employed. The outer loop will choose a word and set the variable count to one. The word chosen by the outer loop will be compared against the remainder of the words in the inner loop.
  • If a match is detected, increase the count by one and make the duplicates of the word '0' to prevent counting it again.
  • If the count of a word is more than one after the inner loop, the word contains duplicates in the string.

C programme for Counting number of repeated words within a string

#include <stdio.h>  
#include <string.h>  
       
int main()  
{     
    char string_array[] = "big black bug bit a big black dog on his big black nose";  
    char words_array[100][100];  
    int i = 0, j = 0, k, length, count;  
          
    // Split the string_array into words, with each row of the words_array representing a single word.  
    for(k=0; string_array[k]!='\0'; k++){  
              
        // The two-dimensional array words_array is represented by the letters i and j.
        if(string_array[k] != ' ' && string_array[k] != '\0'){  
            // The string array is converted to lowercase and added to the words array array.  
            words_array[i][j++] = tolower(string_array[k]);  
        }  
        else{  
            words_array[i][j] = '\0';  
            // To store a new term, increase the row count.  
            i++;  
            //Set column count to 0  
            j = 0;  
        }  
    }  
          
    // Count the number of rows in a variable-length table.  
    length = i+1;  
          
    printf("In the provided string array, there are duplicate words:\n");  
    for(i = 0; i < length; i++){  
        count = 1;  
        for(j = i+1; j < length; j++){  
           if(strcmp(words_array[i], words_array[j]) == 0 && (strcmp(words_array[j],"0") != 0)){  
               count++;  
               // To prevent publishing the visited word, set words array[j] to 0.
               strcpy(words_array[j],"0");  
           }   
        }  
        // If the count is more than one, the duplicate word is shown.
        if(count > 1 )  
            printf("%s\n", words_array[i]);  
    }  
    
    return 0;  
} 

The following output should be generated by this programme:

Output

In the provided string array, there are duplicate words: 
big
black
  • Determine whether the first string is a subsequence of the second

Determine whether string_1 is a subsequence of string_2 given two strings, string_1 and string_2. A subsequence is a sequence that may be created by eliminating some components from another sequence without altering the order of the remaining elements. Time complexity is assumed to be linear. As an example:

  • Input: string_1 = "ABC", string_2 = "ABCXYZ"
  • Output: True (string_1 is a subsequence of string_2)
  • Input: string_1 = "APY", string_2 = "YADXCP"
  • Output: False (string_1 is not a subsequence of string_2)
  • Input: string_1 = "java", string_2 = "javatpoint"
  • Output: True (string_1 is a subsequence of string_2)

The goal here is to see if the length of the longest common subsequence is the same as string_1. If it's equal, it signifies that string_2 contains a subsequence. The implementation utilising the memoization approach is shown below.

C programme for checking whether the first string is a subsequence of the second

// Check if a string is a subsequence of another string with a C++ application.
#include <bits/stdc++.h>
using namespace std;


int arr[1001][1001];


// The length of the longest common subsequence is returned.
int isSubSequence(string& string_1, string& string_2, int i, int j)
{
	if (i == 0 || j == 0) {
		return 0;
	}
	if (arr[i][j] != -1) {
		return arr[i][j];
	}
	if (string_1[i - 1] == string_2[j - 1]) {
		return arr[i][j]
			= 1 + isSubSequence(string_1, string_2, i - 1, j - 1);
	}
	else {
		return arr[i][j] = isSubSequence(string_1, string_2, i, j - 1);
	}
}


/* To test the aforementioned function, using the driver program. */
int main()
{
	string str1 = "jvtont";
	string str2 = "javatpoint";
	int m = str1.size();
	int n = str2.size();
	if (m > n) {
		cout << "NO" << endl;
		return 0;
	}
	arr[m][n];
	memset(arr, -1, sizeof(arr));
	if (isSubSequence(str1, str2, m, n) == m) {
		cout << "YES" << endl;
	}
	else {
		cout << "NO" << endl;
	}
	return 0;
}

The following output should be generated by this programme:

Output

YES

Related Topics

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

5 minutes read.

Linked List Data Structure

Linked list in DS: The linked list is a non-primitive and linear data structure. It is a list of a particular type of data element that is connected to each...

3 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Partitioning a linked list around a given value

Partitioning a linked list around a given value In this problem, we are given a linked list and a value k. We need to partition the given linked list so that...

3 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Binary Tree Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

4 minutes read.

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

Find the nth node from the end of a Linked List

Find the nth node from the end of a Linked List In this problem, we have given a singly linked list and a number 'n,' and we need to find the...

3 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Tree vs Graph: Data Structure

Difference Between Tree and Graph What is Tree? A tree is a non-linear data structure and finite collection of elements called node. A tree, in which the data items are arranged in...

3 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.