Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can get a substring from a string in C#?

Tags:

c#

I have a large string and it’s 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, "

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

like image 623
Riya Avatar asked Mar 05 '11 09:03

Riya


People also ask

How do you get a substring from a string?

To extract a substring that begins at a specified character position and ends before the end of the string, call the Substring(Int32, Int32) method. This method does not modify the value of the current instance. Instead, it returns a new string that begins at the startIndex position in the current string.

Is there a substring function in C?

The substr() function returns the substring of a given string between two given indices. It returns the substring of the source string starting at the position m and ending at position n-1 . The time complexity of above functions is O(n – m). That's all about substr() implementation in C.

Can you slice strings in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.


3 Answers

You could do this manually or using the IndexOf method.

Manually:

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

Using IndexOf, you can see where the full stop is:

int index = myString.IndexOf(".") + 1;
string piece = myString.Substring(index);
like image 93
as-cii Avatar answered Oct 27 '22 15:10

as-cii


string newString = str.Substring(0, 10);

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

See String.Substring Method.

like image 24
richard Avatar answered Oct 27 '22 17:10

richard


Here is an example of getting a substring from the 14th character to the end of the 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 the start index
string substring = text.Substring(14);
like image 4
Adrian Serafin Avatar answered Oct 27 '22 16:10

Adrian Serafin