In previous article, I mentioned how to Serialize List to JSON in C# but now in this article, we will see how to get first character of string in C# or how to get first N characters of string in C# using SubString() and other methods.
Get First Character of string in C#
Let's take a basic example, suppose we have a string and we want only first character of that string, then we can simply use "str[0]
", it will return first character of string "str
"
Example:
string test = "Hello World";
Console.WriteLine(test[0]); // return 'H'
Using SubString
You can also use SubString(startingPosition,Length)
method of C# string, which takes 2 arguments
startingPosition
= position from where we want to start extracting string
length
= character length until we need string (should be less than total length of string)
Considering above example, if we need first 1 character of string using SubString()
string test = "Hello World";
Console.WriteLine(test.Substring(0,1)); // return 'H'
Using Linq
We can also use Linq to get first character from string
char c = test.FirstOrDefault();
//output = "H"
Get First 2 Characters of string in C#
To get the first 2 characters of string in C#, we can use SubString Method, as mentioned above.
Now, the length argument should be 2 instead of 1, as it was in above example, here is complete example
string test = "Hello World";
Console.WriteLine(test.Substring(0,2)); // return 'He'
Here is the complete example
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string test = "Hello World";
Console.WriteLine(test.Substring(0,2)); // return 'He'
Console.WriteLine(test[0]); // return 'H'
Console.WriteLine(test.Substring(0,1)); // return 'H'
Console.WriteLine(test.FirstOrDefault()); // return 'H'
}
}
Get Last Character from String in C#
If you want last character of string in C#, you can simply use SubString()
or using Array Index
, as shown in below code.
string test = "Hello World";
Console.WriteLine(test.Substring(test.Length -1 , 1)); // return 'd'
Console.WriteLine(test[test.Length -1]); // return 'd'
That's it, hope it helps.
You may also like to read:
Multithreading in C# (With example)
File I/O in C# (Read, Write, Delete, Copy file using C#)
Object Oriented Programming (OOPS) concepts in c# with example
C# String