Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do substring in reverse mode in c#

My string is "csm15+abc-indiaurban@v2". I want only "indiaurban" from my string. what I am doing right now is :

var lastindexofplusminus = input.LastIndexOfAny(new char[]{'+','-'});

var lastindexofattherate = input.LastIndexOf('@');

string sub = input.Substring(lastindexofplusminus,lastindexofattherate);

but getting error "Index and length must refer to a location within the string."

Thanks in Advance.

like image 699
N2J Avatar asked Apr 15 '16 04:04

N2J


People also ask

How do you reverse a string in C?

This way, we will have a new string formed by reverse traversal, and this string will be the reversed string. In C language, as we don’t have support for a string data type, we need to use a character array instead. It is easy here to traverse the character array character by character and form a new character array.

What is a substring in C?

C substring: C program to find substring of a string and all substrings of a string. A substring is itself a string that is part of a longer string.

How to print the reverse of a string using while loop?

Let's consider an example to print the reverse of a string using for loop in C programming language. Let's consider an example to print the reverse of a string using while loop in C programming language. char str1 [50], temp; // declare and initialize the size of string array.

How to program a C program using pointers to a string?

C substring program using pointers. To find substring we create a substring function which returns a pointer to string. String address, required length of substring and position from where to extract substring are the three arguments passed to function.


2 Answers

You should put the length in the second argument (instead of passing another index) of the Substring you want to grab. Given that you know the two indexes, the translation to the length is pretty straight forward:

string sub = input.Substring(lastindexofplusminus + 1, lastindexofattherate - lastindexofplusminus - 1);

Note, +1 is needed to get the char after your lastindexofplusminus.
-1 is needed to get the Substring between them minus the lastindexofattherate itself.

like image 182
Ian Avatar answered Sep 16 '22 22:09

Ian


You can simple reverse the string, apply substring based on position and length, than reverse again.

string result = string.Join("", string.Join("", teste.Reverse()).Substring(1, 10).Reverse());

Or create a function:

public static string SubstringReverse(string str, int reverseIndex, int length) {
    return string.Join("", str.Reverse().Skip(reverseIndex - 1).Take(length));
}

View function working here!!

like image 20
Daniel Mendes Avatar answered Sep 17 '22 22:09

Daniel Mendes