Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How extract a specific character in a string in c# by index [duplicate]

Tags:

string

c#

In c++ strings are like array when you write str[i] you can acsess i+1 element of array in there something like that in c# I do not need indexOf method because that is different I need something to bring characters in string by their index

like image 860
Mohammad Reza Rezwani Avatar asked Aug 17 '13 05:08

Mohammad Reza Rezwani


People also ask

How do you extract characters?

To get text following a specific character, you use a slightly different approach: get the position of the character with either SEARCH or FIND, subtract that number from the total string length returned by the LEN function, and extract that many characters from the end of the string.

Which methods are used to extract the characters from string?

The String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf() . The indexOf() methods search forward from the beginning of the string, and the lastIndexOf() methods search backward from the end of the string.

Is there a substring function in C?

So it turns out that, in C, it's actually impossible to write a proper "utility" substring function, that doesn't do any dynamic memory allocation, and that doesn't modify the original string. All of this is a consequence of the fact that C does not have a first-class string type.


1 Answers

Yes, you can reference characters of a string using the same syntax as C++, like this:

string myString = "dummy";
char x = myString[3];

Note: x would be assigned m.

You can also iterate using a for loop, like this:

char y;
for (int i = 0; i < myString.Length; i ++)
{
    y = myString[i];
}

Finally, you can use the foreach loop to get a value already cast to a char, like this:

foreach(char z in myString)
{
    // z is already a char so you can just use it here, no need to cast
}
like image 82
Karl Anderson Avatar answered Sep 20 '22 21:09

Karl Anderson