Saturday, 6 July 2024

Substring in C#

 

Substring

Extracts a substring (portion of string) from a original string.

It contains two overloaded methods.




Method 1 :  startindex  :-  Extracting from a Specific Position to the End of the String

String Name =”Hello John”;

String Output = Name.Substring(6);  // it extract from 6th index onward total characters

 



Method 2 :  startindex , length :-  extracting a Fixed Length Substring from index we provided

String Name =”Hello John”;

String Output = Name.Substring(6,2); // it extracts from 6th index onward total 2 characters

 






Error Handling

  • ArgumentOutOfRangeException: This exception is thrown if the start index or length is out of the bounds of the string.





Real-Time Use Cases

Extracting File Extensions

string fileName = "document.pdf";

string extension = fileName.Substring(fileName.LastIndexOf('.') + 1);  // "pdf"

 

URL Parsing

string url = "https://www.example.com/path?query=123";

string domain = url.Substring(8, url.IndexOf('/', 8) - 8);   // "www.example.com"

 

Date Parsing, Extracting Usernames, Parsing User Input etc.

 

Performance Considerations

  • Immutability: Since strings in C# are immutable, Substring creates a new string, which can impact performance if used excessively in a loop or with large strings.
  • Memory Usage: Each call to Substring results in a new string being allocated in memory. Be mindful of this in performance-critical applications.

Summary

The Substring method is a powerful tool for string manipulation in C#. It allows for precise extraction of parts of a string based on specified positions and lengths. Whether parsing user input, extracting file extensions, or working with dates, Substring is a versatile method that can be applied in many real-world scenarios. However, it is important to handle possible exceptions and consider performance implications when working with large strings or in performance-critical applications.





No comments:

Post a Comment

Thanks for the contribution, our team will check and reply back if response required.