[c#] How to get substring from string in c#?

I have a large string and its stored in a string variable str. And i want to get a substring from that in c#? Suppose the string is : " Retrieves a substring from this instance. The substring starts at a specified character position."

Substring result what i want to display is: The substring starts at a specified character position.

This question is related to c#

The answer is


You could do this manually or using IndexOf method.

Manually:

int index = 43;
string piece = myString.Substring(index);

Using IndexOf you can see where the fullstop is:

int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);

it's easy to rewrite this code in C#...

This method works if your value it's between 2 substrings !

for example:

stringContent = "[myName]Alex[myName][color]red[color][etc]etc[etc]"

calls should be:

myNameValue = SplitStringByASubstring(stringContent , "[myName]")

colorValue = SplitStringByASubstring(stringContent , "[color]")

etcValue = SplitStringByASubstring(stringContent , "[etc]")

Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs

string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);

string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";

string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))

This will cut the part of string which lays between the special characters.


Riya,

Making the assumption that you want to split on the full stop (.), then here's an approach that would capture all occurences:

// add @ to the string to allow split over multiple lines 
// (display purposes to save scroll bar appearing on SO question :))
string strBig = @"Retrieves a substring from this instance. 
            The substring starts at a specified character position. great";

// split the string on the fullstop, if it has a length>0
// then, trim that string to remove any undesired spaces
IEnumerable<string> subwords = strBig.Split('.')
    .Where(x => x.Length > 0).Select(x => x.Trim());

// iterate around the new 'collection' to sanity check it
foreach (var subword in subwords)
{
    Console.WriteLine(subword);
}

enjoy...


string newString = str.Substring(0,10)

will give you the first 10 characters (from position 0 to position 9).

See here.


var data =" Retrieves a substring from this instance. The substring starts at a specified character position.";

var result = data.Split(new[] {'.'}, 1)[0];

Output:

Retrieves a substring from this instance. The substring starts at a specified character position.