Trim A String In C#
Code snippet for how to Trim A String In C# with sample and detail explanation
Simply understanding the concept of trimming a string can be difficult in C#. This article aims to provide an easy walkthrough to learn how to trim a string in C# programming language, with a detailed explanation.
Code Snippet: Trimming a String in C#
Here’s a simple C# program that demonstrates how to trim a string.
using System;
namespace CaveofProgramming
{
class Program
{
static void Main(string[] args)
{
string str = " Hello, World! ";
string trimmedStr = str.Trim();
Console.WriteLine("Before trimming: '{0}'", str);
Console.WriteLine("After trimming: '{0}'", trimmedStr);
}
}
}
When you run this program, it will print:
Before trimming: ' Hello, World! '
After trimming: 'Hello, World!'
Code Explanation for Trimming a String in C#
Let’s break down the given code snippet and understand how each segment of the code contributes to the main function of trimming a string in C#.
-
Firstly, we have the line
using System;
. TheSystem
namespace contains fundamental classes and base classes that define commonly used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. In our case, it gives us access to theString
class which contains theTrim()
function. -
Next, we define a new namespace “CaveofProgramming” and class “Program” within this namespace.
-
Inside the Main() function, we declare a string variable
str
and assign it the value ” Hello, World! ” with leading and trailing white-spaces. -
The line
string trimmedStr = str.Trim();
is where the trimming happens. TheTrim()
function is a built-in function in C# and used to remove all leading and trailing white-spaces from the current string. We assign the result of this operation to a new variabletrimmedStr
. -
Finally,
Console.WriteLine("Before trimming: '{0}'", str);
andConsole.WriteLine("After trimming: '{0}'", trimmedStr);
print the string before and after the trimming action.
Running this code will then provide you with a practical depiction of how the trim function works, demonstrating the removal of the unnecessary white spaces before and after the initial string.