remove character from string c# code example

Example 1: remove all text after string c#

string input = "text?here";
int index = input.LastIndexOf("?"); // Character to remove "?"
if (index > 0)
    input = input.Substring(0, index); // This will remove all text after character ?

Example 2: c# string remove

//using System;
string myString = "Hello Grepper Developers";

/*Removing all characters starting from a position*/
string newStr = myString.Remove(5);
	//remove all characters from string after position 5
	//Output: Hello

/*Removes a specified number of characters after starting from a position*/
string newStr2 = myString.Remove(5, 8); 
	//start from position 5 of string and remove next 8 characters
	//Output: Hello Developers

Example 3: c# remove character from string at index

string s = "This is string";
s = s.Remove(2, 1);
//Output: Ths is string


string s = "This is string";
s = s.Remove(2, 2);
//Output: Th is string

Example 4: c# remove specific character from string

string phrase = "this is, a string with, too many commas";
phrase = phrase.Replace(",", "");

Example 5: C# copy string except for last letter

using System;

class Program
{
    static void Main()
    {
        string input = "OneTwoThree";

        string sub = input.Substring(0, input.Length - 5);
        Console.WriteLine("Substring: {0}", sub);
    }
}

Output

Substring: OneTwo

Example 6: c# Remove String In C#

//The following example removes all characters from a string that are after 25th position in the string.

string founder = "Mahesh Chand is a founder of C# Corner";  
// Remove all characters after first 25 chars  
string first25 = founder.Remove(25);  
Console.WriteLine(first25);  
//************************************   ^_*
//The following example removes 12 characters from the 10th position in the string.

// Remove characters start at the 10th position, next 12 characters  
String newStr = founder.Remove(10, 12);  
Console.WriteLine(newStr);