dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Home » Tip Bank » .NET » C#
Language: .NET
Expertise: Beginner
Mar 1, 2017

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Left, Right and Mid String Functions for C#

Unlike Visual Basic, C# doesn't have built-in string methods to extract parts of string from the Left, Right or a location specified through Mid. Unfortunately you have to create the logic yourself.

Here are examples of Left, Right and Mid in C# with the use of the Substring method present in C# (and VB):

class LeftRightMid
   {
      [STAThread]
      static void Main(string[] args)
      {   
         string myString = "This is a string";
         //Get 4 characters starting from the left
         Console.WriteLine(Left(myString,4));
         //Get 6 characters starting from the right
         Console.WriteLine(Right(myString,6));   
         //Get 4 characters starting at index 5 of the string
         Console.WriteLine(Mid(myString,5,4));
         Console.ReadLine();
      }
      public static string Left(string param, int length)
      {
         string result = param.Substring(0, length);
         return result;
      } 
      public static string Right(string param, int length)
      {
         string result = param.Substring(param.Length - length, length);
         return result;
      }
      public static string Mid(string param,int startIndex, int length)
      {
         string result = param.Substring(startIndex, length);
         return result;
      }
   }
}
Hannes du Preez
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date