Basic String Operations with Implementation
Last Updated :
07 Oct, 2024
In this post, we will look into some of the basic String operations such as:
Let us consider the basic String operations one by one.
Accessing characters by index in a string.
To access any character in a String, we need:
- A non-empty string (say "s")
- A position/index of the character from where it is to be accessed. (say "k")
Using these two, the character can be easily accessed using the below syntax:
char ch = s[k];
OR
char ch = s.charAt(k);
Below is the implementation of the above approach:
C++
// CPP code for accessing an element by index
#include <iostream>
#include <string>
using namespace std;
// Function to demonstrate insert
char accessCharByIndex(string &s, int k)
{
// return the character at Kth index
// in the string str
return s[k];
}
// Driver code
int main()
{
string s("GeeksforGeeks ");
int k = 4;
cout << accessCharByIndex(s, k) << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
// Function to demonstrate accessing character by index
char accessCharByIndex(char* s, int k)
{
// Return the character at the kth index in the string
return s[k];
}
// Driver code
int main()
{
char s[] = "GeeksforGeeks ";
int k = 4;
printf("%c\n", accessCharByIndex(s, k));
return 0;
}
Java
public class GFG {
// Function to demonstrate accessCharByIndex
public static char accessCharByIndex(String s, int k) {
// Return the character at the k-th index in the string s
return s.charAt(k);
}
// Driver code
public static void main(String[] args) {
String s = "GeeksforGeeks ";
int k = 4;
System.out.println(accessCharByIndex(s, k));
}
}
Python
# Function to access an element by index
def access_char_by_index(s, k):
# Return the character at the kth index in the string s
return s[k]
# Driver code
if __name__ == "__main__":
s = "GeeksforGeeks "
k = 4
print(access_char_by_index(s, k))
C#
using System;
class Program {
// Function to access a character by index
static char AccessCharByIndex(string s, int k)
{
// Return the character at the k-th index
return s[k];
}
static void Main()
{
string s = "GeeksforGeeks ";
int k = 4;
Console.WriteLine(AccessCharByIndex(s, k));
}
}
JavaScript
// Function to demonstrate access by index
function accessCharByIndex(s, k) {
// Return the character at the kth index in the string str
return s[k];
}
// Driver code
let s = "GeeksforGeeks ";
let k = 4;
console.log(accessCharByIndex(s, k));
Inserting Character/String into an String.
To insert any Character/String in a String, we need:
- A character/string that is to be inserted in the string (say "ch")
- A position/index of the Character/String where it is to be inserted. (say "k")
Below is the implementation of the above approach:
C++
// CPP code for Inserting character/string into an String.
#include <iostream>
#include <string>
using namespace std;
// Function to demonstrate insert
void insertDemo(string &s, string ch, int k)
{
// Inserts ch at kth index of str
s.insert(k, ch);
cout << "Modified String : " << s << endl;
}
// Driver code
int main()
{
string s("GeeksGeeks ");
string ch = "for";
int k = 5;
cout << "Original String : " << s << endl;
insertDemo(s, ch, k);
return 0;
}
C
#include <stdio.h>
#include <string.h>
void insertDemo(char* s, const char* ch, int k) {
int len1 = strlen(s);
int len2 = strlen(ch);
// Shift characters to the right to make space for ch
for (int i = len1; i >= k; i--) {
s[i + len2] = s[i];
}
// Insert ch at kth index of str
for (int i = 0; i < len2; i++) {
s[k + i] = ch[i];
}
printf("Modified String: %s\n", s);
}
int main() {
char s[] = "GeeksGeeks ";
char ch[] = "for";
int k = 5;
printf("Original String: %s\n", s);
insertDemo(s, ch, k);
return 0;
}
Java
public class Main {
public static void main(String[] args) {
String s = "GeeksGeeks ";
String ch = "for";
int k = 5;
System.out.println("Original String: " + s);
insertDemo(s, ch, k);
}
// Function to demonstrate insert
public static void insertDemo(String s, String ch, int k) {
// Inserts ch at kth index of str
StringBuilder sb = new StringBuilder(s);
sb.insert(k, ch);
String modifiedString = sb.toString();
System.out.println("Modified String: " + modifiedString);
}
}
Python
# Python program for the above approach
# Function to demonstrate insert
def insert_demo(s, ch, k):
# Inserts ch at kth index of s
modified_string = s[:k] + ch + s[k:]
print("Modified String:", modified_string)
# Driver code
if __name__ == "__main__":
s = "GeeksGeeks "
ch_to_insert = "for"
index_to_insert = 5
print("Original String:", s)
insert_demo(s, ch_to_insert, index_to_insert)
C#
using System;
class Program
{
// Function to demonstrate insert
static string InsertDemo(string s, string ch, int k)
{
// Inserts ch at kth index of str
return s.Insert(k, ch);
}
// Driver code
static void Main()
{
string s = "GeeksGeeks ";
string ch = "for";
int k = 5;
Console.WriteLine("Original String: " + s);
string modifiedString = InsertDemo(s, ch, k);
Console.WriteLine("Modified String: " + modifiedString);
}
}
JavaScript
// JavaScript equivalent of the given Java code
// Function to demonstrate insert
function insertDemo(s, ch, k)
{
// Inserts ch at kth index of s
let modifiedString = s.slice(0, k) + ch + s.slice(k);
console.log("Modified String: " + modifiedString);
}
// Call the main function
let s = "GeeksGeeks ";
let ch = "for";
let k = 5;
console.log("Original String: " + s);
insertDemo(s, ch, k);
OutputOriginal String : GeeksGeeks
Modified String : GeeksforGeeks
Modifying character in String
To modify any Character in a String, we need:
- A character that is to replaced in the string (say "ch")
- A position/index of the Character where it is to be replaced at. (say "k")
Below is the implementation of the above approach:
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "Geeks Gor Geeks";
int index = 6;
char ch = 'F';
cout << "Original String = " << s << endl;
s.replace(index, 1, 1, ch);
cout << "Modified String = " << s << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
int main()
{
// Define the string
char s[] = "Geeks Gor Geeks";
// Define the index
int index = 6;
// Define the character
char ch = 'F';
// Print the original string
printf("Original String = %s\n", s);
// Modify the string
s[index] = ch;
// Print the modified string
printf("Modified String = %s\n", s);
return 0;
}
Java
public class GFG {
public static void main(String args[])
{
// Get the String
String s = "Geeks Gor Geeks";
// Get the index
int index = 6;
// Get the character
char ch = 'F';
// Print the original string
System.out.println("Original String = " + s);
s = s.substring(0, index) + ch
+ s.substring(index + 1);
// Print the modified string
System.out.println("Modified String = " + s);
}
}
Python
# Function to replace a character at a specific index in a string
def replace_ch(s, index, ch):
# Convert string to list of characters to allow modification
lst = list(s)
# Replace character at the specified index
lst[index] = ch
# Convert back to string and return
return ''.join(lst)
# Entry point of the program
if __name__ == "__main__":
# Original string
s = "Geeks Gor Geeks"
# Index to replace character
index = 6
# New character
ch = 'F'
# Print original string
print("Original String =", s)
# Replace character at the specified index
s = replace_ch(s, index, ch)
# Print modified string
print("Modified String =", s)
C#
using System;
public class GFG
{
public static void Main()
{
// Get the String
string str = "Geeks Gor Geeks";
// Get the index
int index = 6;
// Get the character
char ch = 'F';
// Print the original string
Console.WriteLine("Original String = " + str);
// Modify the string
str = str.Substring(0, index) + ch + str.Substring(index + 1);
// Print the modified string
Console.WriteLine("Modified String = " + str);
}
}
JavaScript
let str = "Geeks Gor Geeks"; // Get the string
let index = 6; // Get the index
let ch = 'F'; // Get the character
console.log("Original String = " + str); // Print the original string
// Modify the string
str = str.substr(0, index) + ch + str.substr(index + 1);
console.log("Modified String = " + str); // Print the modified string
OutputOriginal String = Geeks Gor Geeks
Modified String = Geeks For Geeks
Deletion of character in String
To delete any Character in a String, we need:
- A character that is to deleted in the string (say "ch")
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void removeChar(string &s, char c)
{
int j = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] != c) {
// Move other characters
s[j++] = s[i];
}
}
// j is new size of the string
s.resize(j);
}
int main()
{
string s = "geeksforgeeks";
removeChar(s, 'g');
cout << s; // Output the modified string
return 0;
}
C
#include <stdio.h>
#include <string.h>
void removeChar(char* s, char c) {
int i, j, n = strlen(s);
for (i = j = 0; i < n; i++) {
if (s[i] != c) {
s[j++] = s[i];
}
}
s[j] = '\0';
}
int main() {
char s[] = "geeksforgeeks";
removeChar(s, 'g');
printf("%s", s);
return 0;
}
Java
public class GfG {
// Function to remove a particular character
// from a StringBuilder
// Parameters:
// - s: the StringBuilder from which
// the character will be removed
// - c: the character to be removed
public static void removeChar(StringBuilder s, char c) {
int j = 0;
// Loop through the StringBuilder
for (int i = 0; i < s.length(); i++) {
// If the current character is not the one to be removed
if (s.charAt(i) != c) {
// Move the character to the position indicated by j
s.setCharAt(j++, s.charAt(i));
}
}
// Delete the remaining characters
s.delete(j, s.length());
}
public static void main(String[] args) {
// Input string as a StringBuilder
StringBuilder s = new StringBuilder("geeksforgeeks");
// Remove character 'g' from the string
removeChar(s, 'g');
// Print the modified string
System.out.println(s);
}
}
Python
def removeChar(s, c):
# Use list comprehension to filter
# out the target character
return ''.join([ch for ch in s if ch != c])
if __name__ == "__main__":
s = "geeksforgeeks"
s = removeChar(s, 'g')
print(s)
JavaScript
// JavaScript program for the above approach
// Function to remove a particular character from a character array
// Parameters:
// - s: the character array from which the character will be removed
// - c: the character to be removed
function removeChar(s, c) {
// Initialize a pointer j to keep track of the position where characters are being moved
let j = 0;
// Loop through the character array
for (let i = 0; i < s.length; i++) {
// If the current character is not the one to be removed
if (s[i] !== c) {
// Move the character to the position indicated by j
s[j++] = s[i];
}
}
// Fill the remaining positions with null characters ('\0')
while (j < s.length) {
s[j++] = '\0';
}
}
// Input string as a character array
let s = "geeksforgeeks".split('');
// Remove character 'g' from the string
removeChar(s, 'g');
// Print the modified string
console.log(s.join(''));
// This code is contributed by Susobhan Akhuli
Concatenating strings (combining multiple strings into one).
To concatenate any String to a String, we need:
- A string that is to appended with the string (say "ch")
Below is the implementation of the above approach:
C++
// C++ Program for string
// concatenation using '+' operator
#include <iostream>
using namespace std;
// Driver code
int main()
{
string init("this is init");
string add(" added now");
// Appending the string.
init = init + add;
cout << init << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char init[] = "this is init";
char add[] = " added now";
char* result = (char*)malloc(strlen(init) + strlen(add) + 1);
strcpy(result, init);
strcat(result, add);
printf("%s\n", result);
free(result);
return 0;
}
Java
public class Main {
public static void main(String[] args) {
String init = "this is init";
String add = " added now";
// Appending the string.
init = init + add;
System.out.println(init);
}
}
Python
def main():
init = "this is init"
add = " added now"
# Concatenate strings
result = init + add
# Print the result
print(result)
# Call the main function
if __name__ == "__main__":
main()
JavaScript
// Define the main function
function main() {
let init = "this is init";
let add = " added now";
// Appending the string.
init = init + add;
console.log(init);
}
// Call the main function
main();
Outputthis is init added now
Finding the length/size of a string
To find the length of the String, we need:
- A string for which the length/size is to be determined (say "str")
Below is the implementation of the above approach:
C++
// C++ program to find length
// of a string
#include <iostream>
#include <string.h>
using namespace std;
// Driver code
int main()
{
// String obj
string str = "GeeksforGeeks";
// size of string object using size() method
cout << str.size() << endl;
return 0;
}
C
#include <stdio.h>
#include <string.h>
int main()
{
// String
char str[] = "GeeksforGeeks";
// Length of string using strlen() function
int length = strlen(str);
printf("%d\n", length);
return 0;
}
Java
public class Main {
public static void main(String[] args)
{
// String object
String str = "GeeksforGeeks";
// Size of string object using length() method
System.out.println(str.length());
}
}
// This code is contributed by Utkarsh
Python
# Main function
def main():
# String object
str = "GeeksforGeeks"
# Size of string object using len() function
print(len(str))
# Calling the main function
if __name__ == "__main__":
main()
JavaScript
// JavaScript program to find length
// of a string
// String
let str = "GeeksforGeeks";
// size of string using length property
console.log(str.length);
Comparing Strings for Equality
C++
// CPP code perform relational
// operation using compare function
#include <iostream>
using namespace std;
void compareFunction(string &s1, string &s2)
{
// comparing both using inbuilt function
int x = s1.compare(s2);
if (x != 0) {
cout << s1 << " is not equal to "
<< s2 << endl;
if (x > 0)
cout << s1 << " is greater than "
<< s2 << endl;
else
cout << s2 << " is greater than "
<< s1 << endl;
}
else
cout << s1 << " is equal to " << s2 << endl;
}
// Driver Code
int main()
{
string s1("geeks");
string s2("forGeeks");
compareFunction(s1, s2);
string s3("geeks");
string s4("geeks");
compareFunction(s3, s4);
return 0;
}
C
#include <stdio.h>
#include <string.h>
void compareStrings(char *s1, char *s2) {
// comparing both using inbuilt function
int x = strcmp(s1, s2);
if (x != 0) {
printf("%s is not equal to %s\n", s1, s2);
if (x > 0) {
printf("%s is greater than %s\n", s1, s2);
} else {
printf("%s is greater than %s\n", s2, s1);
}
} else {
printf("%s is equal to %s\n", s1, s2);
}
}
int main() {
compareStrings("geeks", "forGeeks");
compareStrings("geeks", "geeks");
return 0;
}
Java
public class RelationalOps {
public static void compareStrings(String s1, String s2) {
// comparing both using inbuilt function
int x = s1.compareTo(s2);
if (x != 0) {
System.out.println(s1 + " is not equal to " + s2);
if (x > 0) {
System.out.println(s1 + " is greater than " + s2);
} else {
System.out.println(s2 + " is greater than " + s1);
}
} else {
System.out.println(s1 + " is equal to " + s2);
}
}
public static void main(String[] args) {
compareStrings("geeks", "forGeeks");
compareStrings("geeks", "geeks");
}
}
Python
def compare_strings(s1, s2):
# comparing both using inbuilt comparison
if s1 != s2:
print("s1 is not equal to s2")
if s1 > s2:
print("s1 is greater than s2")
else:
print("s2 is greater than s1")
else:
print("s1 is equal to s2")
# Driver code
compare_strings("geeks", "forGeeks")
compare_strings("geeks", "geeks")
JavaScript
function compareStrings(s1, s2) {
// comparing both using inbuilt comparison
if (s1 !== s2) {
console.log(`${s1} is not equal to ${s2}`);
if (s1 > s2) {
console.log(`${s1} is greater than ${s2}`);
} else {
console.log(`${s2} is greater than ${s1}`);
}
} else {
console.log(`${s1} is equal to ${s2}`);
}
}
// Driver code
compareStrings("geeks", "forGeeks");
compareStrings("geeks", "geeks");
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 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