Search This Blog

Apr 5, 2014

How to extract a portion of a string variable in C#

There are many ways to do this, i am exaplaining two of them.

1. String.Remove Method (Int32, Int32)

Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.

Syntax :

public string Remove(
    int startIndex,
    int count
example :

My string is "C:\Program Files\Microsoft Visual Studio\VSS\users" and i want to

"C:\Program Files\Microsoft Visual Studio\VSS" then

    string s = "svn://mcdssrv/repos/currecnt/class/";
2. String.Substring Method

Retrieves a substring from this instance.

Substring takes the start index (zero-based) and the number of characters you want to copy.

example :

string str = "C:\Program Files\Microsoft Visual Studio\VSS\users";
    str = str.Substring(0, str.LastIndexOf('\') + 1);

3. By using both method

    var subString = "C:\Program Files\Microsoft Visual Studio\VSS\users";
        subString = subString.Remove(subString.LastIndexOf('\')+1);

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...