String in Data Structure



What is a String?

String is a type of primitive data structure that stores a sequence of characters. It is typically used for storing, manipulating, and processing texts such as user input, messages, labels and so on. Each programming language has its own distinct set of rules for representing string. For example, in Java, a string is treated as an object, whereas in C, it is represented as an array of char datatype. In the figure below, we can see a string −

String

In this tutorial, we will explore some of the properties and operations of strings, and how they are implemented in different programming languages.

Syntax

Syntax to create a String in C programming language −

char string_name[string_size] = {chars within single quotes and separated by commas};
or,
char string_name[string_size] = "string in double quotes";

In addition to the above mentioned syntaxes, C++ provides an alternative way for string creation −

string string_name = "string in double quotes";

Creating a string in Java programming language −

String string_name = "string in double quotes";
or,
String string_name = new String("values"); 

Creating a string in Python programming language −

string_name = "string in double quotes"

Need for Strings

String is the most easiest and preferable way of interaction between an application and a user. They are easy to understand and use, as they are based on human-readable characters. Also, they are used to store a wide range of data, such as text, numbers, symbols, binary, hexadecimal, etc.

String Representation

Like arrays, strings are also represented as a collection of buckets where each bucket stores one character. These buckets have index from '0' to 'n-1', where n is the length of that particular string. For instance, a string with size 10 will have buckets indexed from 0 to 9. The figure below illustrates how a string is represented −

String Representation

Following are some important points from the above representation.

  • Index always starts with 0.

  • If the index is from 0 to 9, it means the string has 10 elements.

  • Each character can be accessed via its index.

Basic Operations on a String

There are many operations that can be performed on strings, such as searching, splitting, trimming, indexing and so on. Each programming language has its own set of built-in functions or methods that help in performing these operations with ease.

Following are the basic operations that can be performed on a given string −

  • Concatenation − Joining two or more strings together.
  • Length − Printing the number of characters in a string.
  • Substring − Finding a portion of a bigger string.
  • Reversing − Printing the string characters in reverse order.
  • Indexing − Accessing a particular character using its index.

Concatenation Operation

The concatenation operation is a process of joining two or more strings together to form a new string. For instance, concatenating the two strings "Tutorials" and "Point" will result in "TutorialsPoint". It can be done using different operators or methods, depending on the programming language.

Algorithm

Following is the algorithm to concatenate two strings.

1. Start
2. Declare and Initialize two strings.
3. Perform concatenation.
4. Print the result.
5. Stop

Example

Here, we see a practical implementation of concatenation operation, where we use two different strings to form a new string −

#include <stdio.h>
#include <string.h>
int main(){
   // defining two strings
   char sOne[15] = "Tutorials";
   char sTwo[15] = "Point";
   // concatenating the strings
   strcat(sOne, sTwo); 
   // printing the result
   printf("New String: %s\n", sOne); 
   return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
   // defining two strings
   string sOne = "Tutorials";
   string sTwo = "Point";
   // concatenating the strings
   string newStr = sOne + sTwo; 
   // printing the result
   cout <<"New String: "  << newStr << endl; 
}
public class ConctStr {
   public static void main(String []args){
      // defining two strings
      String sOne = "Tutorials";
      String sTwo = "Point";
	  // concatenating the strings
      String newStr = sOne + sTwo; 
	  // printing the result
      System.out.println("New String: " + newStr); 
   }
}
# defining two strings
sOne = "Tutorials"
sTwo = "Point"
# concatenating the strings
newStr = sOne + sTwo 
# printing the result
print("New String: " + newStr) 

Output

New String: TutorialsPoint

Finding the Length of a String

Finding length of the string means printing the number of characters in that string. For example, the string "Tutorix" has a length of 7. The length of a string can be used to iterate over its characters, access a specific character at a given index, or slice a substring from the original string.

Algorithm

The algorithm to find the length of a string is as follows −

1. Start
2. Declare and Initialize a string.
3. Find the number of characters.
4. Print the result.
5. Stop

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>
#include <string.h>
int main() {
   // the string given as
   char name[] = "tutorialspoint";
   // loop to find the length of given string
   int strLength = 0;
   while (name[strLength] != '\0') {
      strLength++;
   }
   // to print the result
   printf("The length of given string is: %d\n", strLength);
   return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
   // the string given as
   string name = "tutorialspoint";
   // to ind the length of given string
   int strLength = name.length();
   // to print the result
   cout << "The length of given string is: " << strLength << endl;
   return 0;
}
public class Main {
   public static void main(String[] args) {
      // the string given as
      String name = "tutorialspoint";
      // to ind the length of given string
      int strLength = name.length();
      // to print the result
      System.out.println("The length of given string is: " + strLength);
   }
}

# the string given as
name = "tutorialspoint"
# to find the length of given string
length = len(name)
# Print the result
print("The length of given string is:", length) 

Output

The length of given string is: 14

Finding a Substring in a String

A substring refers to a part or subset of a string. In this operation, we need to find the index of the given substring.

Algorithm

Suppose we have a substring named newSubStr and we need to find its index number. Following is the algorithm to find substring.

1. Start
2. Declare and Initialize a string.
3. Define a sub-string.
4. Check index of sub-string.
5. If found, print index of first character of sub-string otherwise print "-1".
6. Stop

Example

In the following example, we are demonstrating this operation in various programming languages −

#include <stdio.h>
#include <string.h>
int main() {
    // Original string
    char orgnlStr[] = "tutorialspoint";
    // Substring to find
    char newSubStr[] = "point";
    // to find the pointer to the substring
    char *indX = strstr(orgnlStr, newSubStr);
    // to check if the substring is present
    if (indX == NULL) {
        printf("-1\n");
    } else {
        printf("Substring found at index: %ld\n", indX - orgnlStr);
    }
    return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
   // Original string
   string orgnlStr = "tutorialspoint";
   // Substring to find
   string newSubStr = "point";
   // to find index of the substring
   int indX = orgnlStr.find(newSubStr);
   // Check if the substring is present
   if (indX == -1) {
      cout << "-1" << endl;
   } else {
      cout << "Substring found at index: " << indX << endl;
   }
   return 0;
}
public class Substr {
   public static void main(String[] args) {
      // Original string
      String orgnlStr = "tutorialspoint";
      // Substring to find
      String newSubStr = "point";
      // to find index of the substring
      int indX = orgnlStr.indexOf(newSubStr);
      // to check if the substring is found
      if (indX == -1) {
         System.out.println("-1");
      } else {
           System.out.println("Substring found at index: " + indX);
      }
   }
}
# Original string
orgnlStr = "tutorialspoint"
# Substring to find
newSubStr = "point"
# to find index of the substring
indX = orgnlStr.find(newSubStr)
# to check if the substring is found
if indX == -1:
   print("-1")
else:
   print("Substring found at index:", indX) 

Output

Substring found at index: 9

Reversing the contents of a String

In the Reversing operation, we reverse the order of characters in a string. This will result in a new string that contains the same characters as the original string, but in the opposite order.

Algorithm

Suppose we have a string and we need to reverse it. Following is the algorithm to reverse a string.

1. Start
2. Declare an empty string.
3. Define a for loop to iterate over the characters of original string.
4. Append each character to the reversed string.
5. Print the result.
6. Stop

Example

Following are the implementations of this operation in various programming languages −

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// function to reverse the string
char* rev_str(char* orgnlStr) {
   int len = strlen(orgnlStr);
   // to store the reversed string
   char* revStr = (char*)malloc(len + 1);
   // loop to reverse the string
   for (int i = 0; i < len; i++) {
      revStr[i] = orgnlStr[len - i - 1];
   }
   // Return the reversed string
   revStr[len] = '\0';
   return revStr;
}
int main() {
    printf("Printing the string in reverse order: \n");
    // calling the function to print the result
    printf("%s\n", rev_str("tutorials")); 
    printf("%s\n", rev_str("point")); 
    return 0;
}
#include <iostream>
#include <string>
using namespace std;
// function to reverse the string
string rev_str(string orgnlStr) {
   // Initializing an empty string 
   string revStr = "";
   // loop to reverse the string
   for (int i = orgnlStr.length() - 1; i >= 0; i--) {
      // Append each character to the reversed string
      revStr += orgnlStr[i];
   }
   // Return the reversed string
   return revStr;
}
int main() {
   cout << "Printing the string in reverse order: " << endl; 
   // calling the function to print the result
   cout << rev_str("tutorials") << endl; 
   cout << rev_str("point") << endl; 
   return 0;
}
public class Main {
   // method to reverse the string
   public static String rev_str(String orgnlStr) {
      // Initializing an empty string 
      String revStr = "";
      // loop to reverse the string
      for (int i = orgnlStr.length() - 1; i >= 0; i--) {
         // Append each character to the reversed string
         revStr += orgnlStr.charAt(i);
      }
      // Return the reversed string
      return revStr;
   }
   public static void main(String[] args) {
      System.out.println("Printing the string in reverse order:"); 
      // calling the method to print the result
      System.out.println(rev_str("tutorials")); 
      System.out.println(rev_str("point")); 
   }
}
# function to reverse the string
def rev_str(orgnlStr):
  # Initializing an empty string 
  revStr = ""
  # loop to reverse the string
  for i in range(len(orgnlStr) - 1, -1, -1):
    # Append each character to the reversed string
    revStr += orgnlStr[i]
  # Return the reversed string
  return revStr
# calling the function to print the result
print("Printing the string in reverse order:")
print(rev_str("tutorials")) 
print(rev_str("point")) 

Output

Printing the string in reverse order: 
slairotut
tniop

Indexing in Strings

In this operation, we try to access or locate a particular character with the help of index.

Algorithm

The algorithm to access a specified character from a given String is as follows −

1. Start
2. Declare and Initialize a string.
3. Find the index number of specified character.
4. Print the result.
5. Stop

Example

Here, we see a practical implementation of indexing operation −

#include <stdio.h>
#include <string.h>
int main(){
   char str[] = "Tutorials Point";
   char *ptr = strchr(str, 'o'); 
   int indX = ptr - str; 
   // print the result
   printf("The index of given character is: %d\n", indX);
   return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
   string str = "Tutorials Point";
   int indX = str.find('o');
   // print the result
   cout << "The index of given character is: " << indX << endl;
   return 0; 
}
public class Main {
   public static void main(String[] args) {
      String str = "Tutorials Point";
      int indX = str.indexOf('o'); 
      System.out.println("The index of given character is: " + indX);
   }  
}
# defining a string
str = "Tutorials Point"
indX = str.find('o')
# print the result
print("The index of given character is:", indX) 

Output

The index of given character is: 3
Advertisements