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.
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.
You can use LINQ:
string input = "csm15+abc-indiaurban@v2";
string result = String.Join("", input.Reverse()
.SkipWhile(c => c != '@')
.Skip(1)
.TakeWhile(c => c != '+' && c != '-')
.Reverse());
Console.WriteLine(result); // indiaurban
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));
}
I don't know what is identify your break point but here is sample which is working
you can learn more about this at String.Substring Method (Int32, Int32)
String s = "csm15+abc-indiaurban@v2";
Char charRange = '-';
Char charEnd = '@';
int startIndex = s.IndexOf(charRange);
int endIndex = s.LastIndexOf(charEnd);
int length = endIndex - startIndex - 1;
Label1.Text = s.Substring(startIndex+1, length);
Assuming that your string is always in that format
string str = "csm15+abc-indiaurban@v2";
string subSTr = str.Substring(10).Substring(0,10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.