Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Basic String Operations with Implementation
Next article icon

Basic String Operations with Implementation

Last Updated : 07 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this post, we will look into some of the basic String operations such as:

Table of Content

  • Accessing characters by index in a string.
  • Inserting Character/String into an String.
  • Modifying character in String
  • Deletion of character in String
  • Concatenating strings (combining multiple strings into one).
  • Finding the length/size of a string
  • Comparing Strings for Equality

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:

  1. A non-empty string (say "s")
  2. 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:

  1. A character/string that is to be inserted in the string (say "ch")
  2. 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);

Output
Original String : GeeksGeeks 
Modified String : GeeksforGeeks 

Modifying character in String

To modify any Character in a String, we need:

  1. A character that is to replaced in the string (say "ch")
  2. 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

Output
Original 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

Output
eeksforeeks

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();

Output
this 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);

Output
13

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");

Next Article
Basic String Operations with Implementation

C

code_r
Improve
Article Tags :
  • Strings
  • DSA
Practice Tags :
  • Strings

Similar Reads

  • Basic Operations in Stack Data Structure with Implementations
    In order to make manipulations in a stack, there are certain operations provided to us for Stack, which include:push() to insert an element into the stackpop() to remove an element from the stacktop() Returns the top element of the stack.isEmpty() returns true if the stack is empty else false.size()
    13 min read
  • Implement *, - and / operations using only + arithmetic operator
    Given two numbers, perform multiplication, subtraction, and division operations on them, using '+' arithmetic operator only. Operations can be performed as follows: Subtraction :- a - b = a + (-1)*b. Multiplication :- a * b = a + a + a ... b times. Division :- a / b = continuously subtract b from a
    12 min read
  • Basic Signal Operations
    Basic signal operations are nothing but signal manipulation or modification tools that are used in signal processing and analysis. It helps to understand the signals in different situations. These operations allow the modification and enhancement of signals for specific applications. In this article
    11 min read
  • Assignment Operators in Programming
    Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improvin
    7 min read
  • Subtract 1 without arithmetic operators
    Write a program to subtract one from a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed. Examples: Input: 12Output: 11Input: 6Output: 5Bitwise Subtraction ApproachTo subtract 1 from a number x (say 0011001000), flip all the bits after the rightmost 1 bit (we
    5 min read
  • Solidity - Assignment Operators
    Solidity is a high-level, statically-typed programming language for Ethereum smart contracts. Python, JavaScript, and C++ impact it. Solidity has several variable and value assignment operators. Solidity supports the following types of operators: Simple Assignment Operator.Arithmetic Assignment Oper
    5 min read
  • Common operations on various Data Structures
    Data Structure is the way of storing data in computer's memory so that it can be used easily and efficiently. There are different data-structures used for the storage of data. It can also be defined as a mathematical or logical model of a particular organization of data items. The representation of
    15+ min read
  • Arithmetic Operators in Solidity
    Arithmetic operators are used to perform arithmetic or mathematical operations. Solidity has the following types of arithmetic operators: Addition: The addition operator takes two operands and results in a sum of these operands. It is denoted by +.Subtraction: The subtraction operator takes two oper
    2 min read
  • Basic Operators in Java
    Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic
    10 min read
  • What are Operators in Programming?
    Operators in programming are essential symbols that perform operations on variables and values, enabling tasks like arithmetic calculations, logical comparisons, and bitwise manipulations. In this article, we will learn about the basics of operators and their types. Operators in Programming Table of
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences