Left, Right and Mid functions in C#


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. namespace LeftRightMid
  2. {
  3. ///
  4. /// Summary description for Class1.
  5. ///
  6. class LeftRightMid
  7. {
  8. ///
  9. /// The main entry point for the application.
  10. ///
  11. [STAThread]
  12. static void Main(string[] args)
  13. {
  14.  
  15. //assign a value to our string
  16. string myString = "This is a string";
  17. //get 4 characters starting from the left
  18. Console.WriteLine(Left(myString,4));
  19. //get 6 characters starting from the right
  20. Console.WriteLine(Right(myString,6));
  21. //get 4 characters starting at index 5 of the string
  22. Console.WriteLine(Mid(myString,5,4));
  23. //get the characters from index 5 up to the end of the string
  24. Console.WriteLine(Mid(myString,5));
  25. //display the result to the screen
  26. Console.ReadLine();
  27. }
  28.  
  29. public static string Left(string param, int length)
  30. {
  31. //we start at 0 since we want to get the characters starting from the
  32. //left and with the specified lenght and assign it to a variable
  33. string result = param.Substring(0, length);
  34. //return the result of the operation
  35. return result;
  36. }
  37. public static string Right(string param, int length)
  38. {
  39. //start at the index based on the lenght of the sting minus
  40. //the specified lenght and assign it a variable
  41. string result = param.Substring(param.Length - length, length);
  42. //return the result of the operation
  43. return result;
  44. }
  45.  
  46. public static string Mid(string param,int startIndex, int length)
  47. {
  48. //start at the specified index in the string ang get N number of
  49. //characters depending on the lenght and assign it to a variable
  50. string result = param.Substring(startIndex, length);
  51. //return the result of the operation
  52. return result;
  53. }
  54.  
  55. public static string Mid(string param,int startIndex)
  56. {
  57. //start at the specified index and return all characters after it
  58. //and assign it to a variable
  59. string result = param.Substring(startIndex);
  60. //return the result of the operation
  61. return result;
  62. }
  63.  
  64. }
  65. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.