In this article, I have mentioned how we can remove the last character from a string in C# using the console application example. To remove last character from string we will use String.Remove() Method in C#, using which we can also replace the last character from string.
Remove() Method has 2 overload methods:
Remove(Int32)
: Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.Remove(Int32, Int32)
: Returns a new string in which a specified number of characters in the current instance beginning at a specified position has been deleted.
Let's take a look at various example using String.Remove() Method in C#
Remove the Last Character from string in C#
In this example, we will create a string "Hello World," and remove "," last character from the string by passing 2 arguments in the Remove method.
First argument, we will position from where we need to remove characters and the second length of characters which we want to remove.
using System;
namespace StringRemove
{
public class Program
{
static void Main(string[] args)
{
var str = "Hello World,";
string minusNew = str.Remove(str.Length - 1, 1);
Console.WriteLine(minusNew);
//output: Hello World
}
}
}
Output:
Hello World
Remove All characters after a specific position of the string in C#
Now, if you want to remove all characters from the string after a certain length, we can use string.Remove() and pass only 1 argument, that is the position from where we want to remove the character until the end.
var str = "Hello World, new";
string minusNew = str.Remove(str.Length - 5);
Console.WriteLine(minusNew);
//output: Hello World
Remove All Characters in Between a C# String
Now, if you want to remove characters in between a string, then you can use the below C# Code example:
using System;
namespace StringRemove
{
public class Program
{
static void Main(string[] args)
{
var str = "Hello World, new";
// Remove characters start at 4th position, next 5 characters
String newStr = str.Remove(4, 5);
Console.WriteLine(newStr);
//get position of word - 'World'
int pos = str.IndexOf("World");
if (pos >= 0)
{
// String after 'World'
string afterWorld = str.Remove(pos);
Console.WriteLine(afterWorld);
// Remove everything before World but include World
string beforeWorld = str.Remove(0, pos);
Console.WriteLine(beforeWorld);
}
}
}
}
Output:
Hellld, new
Hello
World, new
That's it, hope it helps.
You may also like to read:
System.Text.Json Serialize / Deserialize Object in C#
What is Console.Log Equivalent in C#?
Fibonacci series In C# (Various possible ways)
Create a calculator in C# console application