Skip to content
- Courses
- DSA to Development
- Newly Launched!
- For Working Professionals
- For Students
- GATE Exam Courses
- All Courses
- Tutorials
- Data Structures & Algorithms
- DSA for Beginners
- Data Structures
- Algorithms
- Complete DSA Tutorial
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top 100 DSA Interview Questions Topic-wise
- 100 Days of Code
- Python
- ML & Data Science
- Machine Learning
- Data Science Tutorial
- Data Science Packages
- Data Visualization
- Data Analysis
- Deep Learning
- NLP Tutorial
- OpenCV Tutorial
- Interview Questions
- System Design
- Interview Corner
- Languages
- Web Development
- HTML
- CSS
- JavaScript
- TypeScript
- ReactJS
- Node.js
- PHP
- AngularJS
- jQuery
- Web Development Using Python
- Web Design
- 100 Days of Web Development
- CS Subjects
- DevOps And Linux
- School Learning
- GATE
- GeeksforGeeks Videos
- Data Structures & Algorithms
- Jobs
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Contests
-
Last Updated : 21 Oct, 2021
Summarize
Comments
Improve
Given a string as an input we need to find all the substrings present in the given string.
Example:
Input:geeksOutput:geeksgeeeekksgeeeekeksgeekeeksgeeksInput:abOutput:abab
Method 1: Using Substring() method
We can find all the substrings from the given string using the Substring() method. This method returns a substring from the current string. It contains two parameters where the first parameter represents the starting position of the substring which has to be retrieved and the second parameter will represent the length of the substring. Here if the first parameter is equal to the length of the string then this method will return nothing.
Syntax:
str.Substring(strindex, strlen)
where strindex is the starting index of the substring and strlen is the length of the substring.
Approach
To display
- Read the string from the user.
- Write the find_substrings() function to get substrings.
- In find_substrings() function call Substring() method to get the substrings.
for(i = 1; i <= input_string.Length; i++){ for (j = 0; j <= input_string.Length - i; j++) { // Use Substring function Console.WriteLine(input_string.Substring(j, i)); }}
- Now show the retrieved substrings.
Example:
C#
// C# program to display all Substrings
// present in the given String
using
System;
class
GFG{
// Function to get the substrings
static
void
find_substrings(
string
input_string)
{
int
j = 0;
int
i = 0;
for
(i = 1; i <= input_string.Length; i++)
{
for
(j = 0; j <= input_string.Length - i; j++)
{
// Using Substring() function
Console.WriteLine(input_string.Substring(j, i));
See AlsoString.EndsWith Method (System)How to Check if a String Contains Another String in C# 🔍How to Use Substring in C#: A Detailed Guide - ByteHideString.Substring Method (System)}
}
}
// Driver code
public
static
void
Main()
{
// Declare the main string
string
input_string;
Console.Write(
"Enter String : "
);
Console.Write(
"\n"
);
// Read the string
input_string = Console.ReadLine();
// Call the function
find_substrings(input_string);
}
}
Output:
Enter String :GFGGFGGFFGGFG
Method 2: Using for loop
We can also find substring from the given string using nested for loop. Here the outer for loop is used to select starting character, mid for loop is used to considers all characters on the right of the selected starting character as the ending character of the substring, and the inner for loop is used to print characters from the starting to the ending point.
Example:
C#
// C# program to display all Substrings
// present in the given String
using
System;
class
GFG{
// Function to print all substrings
// from the given string
static
void
find_Substring(
string
inputstr,
int
n)
{
// Choose starting point
for
(
int
l = 1; l <= n; l++)
{
// Choose ending point
for
(
int
i = 0; i <= n - l; i++)
{
// Display the substrings
int
q = i + l - 1;
for
(
int
j = i; j <= q; j++)
Console.Write(inputstr[j]);
Console.WriteLine();
}
}
}
// Driver code
static
public
void
Main ()
{
string
inputstr =
"Geeks"
;
// Calling function
find_Substring(inputstr, inputstr.Length);
}
}
Output:
GeeksGeeeekksGeeeekeksGeekeeksGeeks
Please Login to comment...
Similar Reads
Different Ways to Convert Char Array to String in C#
We have given a character array arr and the task is to convert char array to string str in C#. Input: arr = [s, t, r, i, n, g] Output: string Input: arr = [G, e, e, k, s, F, o, r, G, e, e, k, s] Output: GeeksForGeeks In order to do this task, we have the following methods: Method 1: Using string() Method: The String class has several overloaded con
3 min read
Different ways to create an Object in C#
A fully object-oriented language means everything is represented as an object but can't differentiate between primitive types and objects of classes but C# is not purely object oriented since it supports many procedural programming concepts such as pointers to an extent. An object is a basic unit of Object Oriented Programming and represents the re
4 min read
Different ways to sort an array in descending order in C#
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Arranging the array's elements from largest to smallest is termed as sorting the array in descending order. Examples: Input : array = {5, 9, 1, 4, 6, 8}; Output : 9, 8, 6, 5, 4, 1 Input : array = {1, 9, 6, 7, 5, 9
4 min read
Different ways to make Method Parameter Optional in C#
As the name suggests optional parameters are not compulsory parameters, they are optional. It helps to exclude arguments for some parameters. Or we can say in optional parameters, it is not necessary to pass all the parameters in the method. This concept is introduced in C# 4.0. Here we discuss the different ways to implement the optional parameter
4 min read
Different Ways to Convert Double to Integer in C#
Given a Double real number, the task is to convert it into Integer in C#. There are mainly 3 ways to convert Double to Integer as follows: Using Type CastingUsing Math.round()Using Decimal.ToInt32() Examples: Input: double = 3452.234 Output: 3452 Input: double = 98.23 Output: 98 1. Using Typecasting: This technique is a very simple and user friendl
2 min read
File.Replace(String, String, String) Method in C# with Examples
File.Replace(String, String, String) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file and creates a backup of the replaced file.Syntax: public static void Replace (string sourceFileName, string destinationFileName, string destinati
3 min read
File.Replace(String, String, String, Boolean) Method in C# with Examples
File.Replace(String, String, String, Boolean) is an inbuilt File class method that is used to replace the contents of a specified destination file with the contents of a source file then it deletes the source file, creates a backup of the replaced file, and optionally ignores merge errors. Syntax: public static void Replace (string sourceFileName,
3 min read
C# Program to Read a String and Find the Sum of all Digits
Given a string, our task is to first read this string from the user then find the sum of all the digits present in the given string. Examples Input : abc23d4 Output: 9 Input : 2a3hd5j Output: 10 Approach: To reada String and find the sum of all digits present in the string follow the following steps: First of all we read the string from the user us
2 min read
Different Methods to Read a Character in C#
In C#, we know that Console.Read() method is used to read a single character from the standard output device. And also there are different methods available to read the single character. Following methods can be used for this purpose: Console.ReadLine()[0] MethodConsole.ReadKey().KeyChar MethodChar.TryParse() MethodConvert.ToChar() MethodConsole.Re
3 min read
Different Types of HTML Helpers in ASP.NET MVC
ASP.NET provides a wide range of built-in HTML helpers that can be used as per the user's choice as there are multiple overrides available for them. There are three types of built-in HTML helpers offered by ASP.NET. 1. Standard HTML Helper The HTML helpers that are mainly used to render HTML elements like text boxes, checkboxes, Radio Buttons, and
5 min read
Reverse all the word in a String represented as a Linked List
Given a Linked List which represents a sentence S such that each node represents a letter, the task is to reverse the sentence without reversing individual words. For example, for a given sentence "I love Geeks for Geeks", the Linked List representation is given as: I-> ->l->o->v->e-> ->G->e->e->k->s-> ->f-
15 min read
C# | Equals(String, String) Method
In C#, Equals(String, String) is a String method. It is used to determine whether two String objects have the same value or not. Basically, it checks for equality. If both strings have the same value, it returns true otherwise returns false. This method is different from Compare and CompareTo methods. This method compares two string on the basis of
2 min read
C# | How to copy a String into another String
String.Copy(String) Method is used to create a new instance of String with the same value as a specified String. In other words, this method is used to copy the data of one string into a new string. The new string contains same data like an original string but represents a different object reference. Syntax: public static string Copy (string value)
2 min read
File.Copy(String, String) Method in C# with Examples
File.Copy(String, String) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file which is created by this function. Syntax: public static void Copy (string sourceFileName, string destFileName); Parameter: This function accepts two parameters which are illustrated below: sourc
3 min read
File.AppendAllText(String, String) Method in C# with Examples
File.AppendAllText(String, String) is an inbuilt File class method which is used to append the specified string to the given file if that file exists else creates a new file and then appending is done. It also closes the file.Syntax: public static void AppendAllText (string path, string contents); Parameter: This function accepts two parameters whi
3 min read
File.AppendAllText(String, String, Encoding) Method in C# with Examples
File.AppendAllText(String, String, Encoding) is an inbuilt File class method which is used to append the specified string to the given file using the specified encoding if that file exists else creates a new file and then appending is done. Syntax: public static void AppendAllText (string path, string contents, System.Text.Encoding encoding); Param
3 min read
File.WriteAllText(String, String) Method in C# with Examples
File.WriteAllText(String, String) is an inbuilt File class method that is used to create a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten. Syntax: public static void WriteAllText (string path, string contents); Parameter: This function accepts two parameters which ar
3 min read
File.WriteAllText(String, String, Encoding) Method in C# with Examples
File.WriteAllText(String, String, Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten. Syntax: public static void WriteAllText (string path, string contents, System.Text.Encodi
3 min read
File.WriteAllLines(String, String[], Encoding) Method in C# with Examples
File.WriteAllLines(String, String[], Encoding) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.Syntax: public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding); Parameter: This function a
3 min read
File.WriteAllLines(String, String[]) Method in C# with Examples
File.WriteAllLines(String, String[]) is an inbuilt File class method that is used to create a new file, writes the specified string array to the file, and then closes the file.Syntax: public static void WriteAllLines (string path, string[] contents); Parameter: This function accepts two parameters which are illustrated below: path: This is the spec
3 min read
File.WriteAllLines(String, IEnumerable<String>, Encoding) Method in C# with Examples
File.WriteAllLines(String, IEnumerable<String>, Encoding) is an inbuilt File class method that is used to create a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file. Syntax: public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<String> contents,
3 min read
File.WriteAllLines(String, IEnumerable<String>) Method in C# with Examples
File.WriteAllLines(String, IEnumerable<String>) is an inbuilt File class method that is used to create a new file, writes a collection of strings to the file, and then closes the file. Syntax: public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<String>contents); Parameter: This function accepts two para
3 min read
File.Copy(String, String, Boolean) Method in C# with Examples
File.Copy(String, String, Boolean) is an inbuilt File class method that is used to copy the content of the existing source file content to another destination file if exist, else create a new destination file then copying process is done.Syntax: public static void Copy (string sourceFileName, string destFileName, bool overwrite); Parameter: This fu
4 min read
File.AppendAllLines(String, IEnumerable<String>, Encoding) Method in C# with Examples
File.AppendAllLines(String, IEnumerable<String>, Encoding) is an inbuilt File class method which is used to append specified lines to a file by using a specified encoding and then closes the file. If the specified file does not exist, this method creates a new file, writes the specified lines to the file, and then closes the file. Syntax: pub
3 min read
File.AppendAllLines(String, IEnumerable<String>) Method in C# with Examples
File.AppendAllLines(String, IEnumerable<String>) is an inbuilt File class method which is used to append specified lines to a file and then closes the file. Syntax: public static void AppendAllLines (string path, System.Collections.Generic.IEnumerable<String> contents); Parameter: This function accepts two parameters which are illustrat
3 min read
Difference between String and string in C#
String is an alias for System.String class and instead of writing System.String one can use String which is a shorthand for System.String class and is defined in the .NET base class library. The size of the String object in memory is 2GB and this is an immutable object, we can not modify the characters in a string once declared, but we can delete i
2 min read
C# | Remove all elements in a collection from a HashSet
In C#, you can use the ExceptWith() method to remove all the elements in a collection from a HashSet. The ExceptWith() method removes all the elements in the specified collection from the current HashSet. Here is an example code that demonstrates how to use the ExceptWith() method to remove all the elements in a collection from a HashSet: C/C++ Cod
3 min read
C# | Remove all objects from the Stack
Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. Stack<T>.Clear Method is used to Removes all objects from the Stack<T>. This method is an O(n) o
3 min read
C# | Remove all objects from the Queue
Queue represents a first-in, first out collection of object. It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue, and when you remove an item, it is called deque. Queue. Clear Method is used to remove the objects from the Queue. This method is an O(n) operation, where n is total cou
3 min read
C# | Remove all elements from the Hashtable
The Hashtable class represents a collection of key-and-value pairs that are organized based on the hash code of the key. The key is used to access the items in the collection. Hashtable.Clear Method is used to remove all elements from the Hashtable. Syntax: myTable.Clear() Here myTable is the name of the Hashtable. Exceptions: This method will give
2 min read
Article Tags :
Trending in News
- OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
- How to Merge Cells in Google Sheets: Step by Step Guide
- How to Lock Cells in Google Sheets : Step by Step Guide
- PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
- #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank
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
'); $('.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, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('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) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); 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"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); 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"); $('.improvement-reason-modal').hide(); } }, }); } 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{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').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; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { 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(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); 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"); $('.improvement-reason-modal').hide(); } }, }); });
Continue without supporting 😢