×

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

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Huffman tree in Data Structures

The Huffman trees in the field of data structures are pretty impressive in their work. They are generally treated as the binary tree, which is linked with the least external...

6 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.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

Deletion in B+ Tree

Make a search for the leaf node that containing the key value by taking the value in a key value. If the required key value is found, then it will remove...

6 minutes read.

Lowest common ancestor in a binary search tree

Suppose you have given two values of nodes in a binary search tree. You have to find out the lowest common ancestor between the nodes. Let’s take an example tree- For the...

4 minutes read.

Given a Binary Tree, find its Minimum Depth

Implementation // Creating a C++ program or implementation to search and explore the minimum depth of a given binary tree.  #include<bits/stdc++.h> using namespace std; // Creating a new binary tree node struct __nod { int record; struct __nod*...

5 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.

Remove duplicates from an unsorted Linked List

Remove duplicates from an unsorted Linked List This article will explain how we can remove duplicates from unsorted linked lists. Here we have given an unsorted singly linked list and will...

3 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.

Recursion - Factorial and Fibonacci

In this article, we will learn how to find the factorial of a number and the Fibonacci series up to n using the recursion method. What is recursion? Defining anything in terms...

7 minutes read.

Bucket Sort

Bucket Sort: In the sorting algorithm, we create buckets and put elements into them. We can apply some sorting algorithm (insertion sort) to sort the elements in each bucket. Finally,...

4 minutes read.

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...

9 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Strictly binary tree in Data Structures?

What is a strictly Binary Tree in Data Structures? There are various kinds of binary trees that we know exist in data structures, and they all have their purposes. In this...

4 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

Advantages and Disadvantages of Linked List

Advantages of Linked List The linked list is a dynamic data structure.You can also decrease and increase the linked list at run-time. That is, you can allocate and deallocate memory at...

3 minutes read.

What is the difference between DFS and BFS?

What is BFS? BFS is generally known as the low level traversal. As we already know that it stands for breadth first search and is mainly used in the queue data...

4 minutes read.