Introduction to Strings - Data Structure and Algorithm Tutorials
Last Updated :
23 Jul, 2025
Strings are sequences of characters. The differences between a character array and a string are, a string is terminated with a special character ‘\0’ and strings are typically immutable in most of the programming languages like Java, Python and JavaScript. Below are some examples of strings:
"geeks" , "for", "geeks", "GeeksforGeeks", "Geeks for Geeks", "123Geeks", "@123 Geeks"
How Strings are represented in Memory?
In C, a string can be referred to either using a character pointer or as a character array. When strings are declared as character arrays, they are stored like other types of arrays in C. String literals (assigned to pointers) are immutable in C and C++.
In C++, strings created using string class are mutable and internally represented as arrays. In Python, Java and JavaScript, strings characters are stored at contiguous locations (like arrays).
How to Declare Strings in various languages?
- C: Strings are declared as character arrays or pointers and must end with a null character (
\0
) to indicate termination. - C++: Supports both C-style character arrays and the
std::string
class, which provides built-in functions for string manipulation. - Java: Strings are immutable objects of the
String
class, meaning their values cannot be modified once assigned. - Python: Strings are dynamic and can be declared using single, double, or triple quotes, making them flexible for multi-line text handling.
- JavaScript: Strings are primitive data types and can be defined using single, double, or template literals (
backticks
), allowing for interpolation. - C#: Uses the
string
keyword, which represents an immutable sequence of characters, similar to Java. - There is no character type on Python and JavaScript and a single character is also considered as a string.
Below is the representation of strings in various languages:
C++
// C++ program to demonstrate String
// using Standard String representation
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Declare and initialize the string
string str1 = "Welcome to GeeksforGeeks!";
// Initialization by raw string
string str2("A Computer Science Portal");
// Print string
cout << str1 << endl << str2;
return 0;
}
C
// C program to illustrate strings
#include <stdio.h>
int main()
{
// declare and initialize string
char str[] = "Geeks";
// print string
printf("%s", str);
return 0;
}
Java
// Java code to illustrate String
import java.io.*;
import java.lang.*;
class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String s = "GeeksforGeeks";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
// Prints the String.
System.out.println("String s1 = " + s1);
}
}
Python
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
C#
// Include namespace system
using System;
public class Test
{
public static void Main(String[] args)
{
// Declare String without using new operator
var s = "GeeksforGeeks";
// Prints the String.
Console.WriteLine("String s = " + s);
// Declare String using new operator
var s1 = new String("GeeksforGeeks");
// Prints the String.
Console.WriteLine("String s1 = " + s1);
}
}
JavaScript
// Declare and initialize the string
let str1 = "Welcome to GeeksforGeeks!";
// Initialization using another method
let str2 = new String("A Computer Science Portal");
// Print strings
console.log(str1);
console.log(str2.toString());
PHP
<?php
// single-quote strings
$site = 'Welcome to GeeksforGeeks';
echo $site;
?>
Are Strings Mutable in Different Languages?
- In C/C++, string literals (assigned to pointers) are immutable.
- In C++, string objects are mutable.
- In Python, Java and JavaScript, strings are immutable.
C++
#include <iostream>
using namespace std;
int main() {
const char* str = "Hello, world!";
str[0] = 'h'; // Error : Assignment to read only
cout << str;
return 0;
}
C
#include <stdio.h>
int main() {
char *str = "Hello, world!";
str[0] = 'h'; // Undefined behavior
printf("%s\n", str);
return 0;
}
Java
// Java Program to demonstrate why
// Java Strings are immutable
import java.io.*;
class GfG {
public static void main(String[] args) {
String s1 = "java";
s1.concat(" rules");
// s1 is not changed because strings are
// immutable
System.out.println("s1 refers to " + s1);
}
}
Python
# Create an immutable string
s = "GFG"
# This will cause a error
# because strings are immutable
s[1] = 'f'
print(s)
JavaScript
let str = "GFG";
str[1] = "f";
console.log(str); // Output: "GFG" (unchanged)
General Operations performed on String
Here we are providing you with some must-know concepts of string:
- Length of String : The length of a string refers to the total number of characters present in it, including letters, digits, spaces, and special characters. It is a fundamental property of strings in any programming language and is often used in various operations such as validation, manipulation, and comparison.
- Search a Character : Searching for a character in a string means finding the position where a specific character appears. If the character is present multiple times, you might need to find its first occurrence, last occurrence, or all occurrences.
- Check for Substring : Checking for a substring means determining whether a smaller sequence of characters exists within a larger string. A substring is a continuous part of a string, and checking for its presence is a common operation in text processing, search algorithms, and data validation.
- Insert a Character : Inserting a character into a string means adding a new character at a specific position while maintaining the original order of other characters. Since strings are immutable in many programming languages, inserting a character usually involves creating a new modified string with the desired character placed at the specified position.
- Delete a Character : Deleting a character from a string means removing a specific character at a given position while keeping the remaining characters intact. Since strings are immutable in many programming languages, this operation usually involves creating a new string without the specified character.
- Check for Same Strings : Checking if two strings are the same means comparing them character by character to determine if they are identical in terms of length, order, and content. If every character in one string matches exactly with the corresponding character in another string, they are considered the same.
- String Concatenation : String concatenation is the process of joining two or more strings together to form a single string. This is useful in text processing, formatting messages, constructing file paths, or dynamically creating content.
- Reverse a String : Reversing a string means arranging its characters in the opposite order while keeping their original positions intact in the reversed sequence. This operation is commonly used in text manipulation, data encryption, and algorithm challenges.
- Rotate a String Rotating a string means shifting its characters to the left or right by a specified number of positions while maintaining the order of the remaining characters. The characters that move past the boundary wrap around to the other side.
- Check for Palindrome : Checking for a palindrome means determining whether a string reads the same forward and backward. A palindrome remains unchanged when reversed, making it a useful concept in text processing, algorithms, and number theory.
Introduction to Strings - Data Structure and Algorithm Tutorials - FAQs
Is string a linear data structure?
Yes, string is a linear data structure.
Where are strings used?
It is used to store the sequence of characters.
Is string a data type?
A string is generally considered a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of elements, typically characters, using some character encoding.
Why is text called string?
Text are also called string because it consists of sequence of characters like string.
What are characters in a string?
Each digit in a string is a character and character is a single visual object used to represent text, numbers, or symbols.
Search a Character
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem