数据结构和算法

DSA - 主页 DSA - 概述 DSA - 环境设置 DSA - 算法基础 DSA - 渐近分析

数据结构

DSA - 数据结构基础 DSA - 数据结构和类型 DSA - 数组数据结构

链接列表

DSA - 链接列表数据结构 DSA - 双向链接列表数据结构 DSA - 循环链表数据结构

堆栈 &队列

DSA - 堆栈数据结构 DSA - 表达式解析 DSA - 队列数据结构

搜索算法

DSA - 搜索算法 DSA - 线性搜索算法 DSA - 二分搜索算法 DSA - 插值搜索 DSA - 跳跃搜索算法 DSA - 指数搜索 DSA - 斐波那契搜索 DSA - 子列表搜索 DSA - 哈希表

排序算法

DSA - 排序算法 DSA - 冒泡排序算法 DSA - 插入排序算法 DSA - 选择排序算法 DSA - 归并排序算法 DSA - 希尔排序算法 DSA - 堆排序 DSA - 桶排序算法 DSA - 计数排序算法 DSA - 基数排序算法 DSA - 快速排序算法

图形数据结构

DSA - 图形数据结构 DSA - 深度优先遍历 DSA - 广度优先遍历 DSA - 生成树

树数据结构

DSA - 树数据结构 DSA - 树遍历 DSA - 二叉搜索树 DSA - AVL 树 DSA - 红黑树 DSA - B树 DSA - B+ 树 DSA - 伸展树 DSA - 尝试 DSA - 堆数据结构

递归

DSA - 递归算法 DSA - 使用递归的汉诺塔 DSA - 使用递归的斐波那契数列

分而治之

DSA - 分而治之 DSA - 最大最小问题 DSA - 施特拉森矩阵乘法 DSA - Karatsuba 算法

贪婪算法

DSA - 贪婪算法 DSA - 旅行商问题(贪婪方法) DSA - Prim 最小生成树 DSA - Kruskal 最小生成树 DSA - Dijkstra 最短路径算法 DSA - 地图着色算法 DSA - 分数背包问题 DSA - 作业排序截止日期 DSA - 最佳合并模式算法

动态规划

DSA - 动态规划 DSA - 矩阵链乘法 DSA - Floyd Warshall 算法 DSA - 0-1 背包问题 DSA - 最长公共子序列算法 DSA - 旅行商问题(动态方法)

近似算法

DSA - 近似算法 DSA - 顶点覆盖算法 DSA - 集合覆盖问题 DSA - 旅行商问题(近似方法)

随机算法

DSA - 随机算法 DSA - 随机快速排序算法 DSA - Karger 最小割算法 DSA - Fisher-Yates 洗牌算法

DSA 有用资源

DSA - 问答 DSA - 快速指南 DSA - 有用资源 DSA - 讨论


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
", 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
", 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
");
    } else {
        printf("Substring found at index: %ld
", 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: 
");
    // calling the function to print the result
    printf("%s
", rev_str("tutorials")); 
    printf("%s
", 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
", 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