[英]How to get the last five characters of a string using Substring() in C#?
[英]How create substring when i know first and last characters in the string with C#?
我是C#的新手,請幫助以高效的C#方式編寫。
大小寫(始終第一個字符為“-”,最后一個字符為“>”):
范例1:
input: bdfdfd-wr>
output: wr
范例2:
input: -dsdsds-sdsds-grtt>
output: grtt
范例3:
input: -dsdsds-sdsds-grtt>><>>dfdfdfd
output: grtt
范例4:
input: -dsdsds-sdsds-grtt>><->>df-d=fdfd
output: grtt
string example = "-dsdsds-sdsds-grtt>";
int lastIndexOfHyphen = example.LastIndexOf("-");
int indexOfBracket = example.IndexOf(">", lastIndexOfHyphen);
string substr = example.Substring(lastIndexOfHyphen + 1, indexOfBracket - lastIndexOfHyphen - 1);
我可以想到兩種方式:
-([az]+)>
。 結果將在Match .Groups[1]
。 >
,使用LastIndexOf查找最后的破折號,然后使用Substring獲取單詞。 您可以使用正則表達式 。
例:
var r = new Regex(@"-(\w*)>");
var inputs = new [] { "bdfdfd-wr>",
"-dsdsds-sdsds-grtt>",
"-dsdsds-sdsds-grtt>><>>dfdfdfd",
"-dsdsds-sdsds-grtt>><->>df-d=fdfd" };
foreach(var i in inputs)
Console.WriteLine(r.Match(i).Groups[1].Value);
輸出:
wr
grtt
grtt
grtt
string s = "-dsdsds-sdsds-grtt>";
string output = null;
if (s.Contains(">"))
{
output = s.Split(new string[] { ">" },
StringSplitOptions.RemoveEmptyEntries)
.FirstOrDefault(i => i.Contains("-"));
if (output != null)
output = output.Substring(output.LastIndexOf("-") + 1);
}
返回包裝在-和>中的第一行文本。 如果輸入為"-dsdsds-sdsds-grtt>asdas-asq>"
,它將返回grtt
; 對於-dsdsds-sdsds-grtt>><>>dfdfdfd
返回grtt
在這里,您可以找到許多使用字符串的方法。
string input = "-dsdsds-sdsds-grtt>";
int startInd = input.LastIndexOf('-');
int endInd = input.IndexOf('>', startInd);
string result;
if (startInd < endInd)
result = input.Substring(startInd + 1, endInd - startInd - 1);
編輯:
string input = "-dsdsds-sdsds-grtt>><->>df-d=fdfd";
string str = input.Substring(0, input.IndexOf('>'));
string result = str.Substring(str.LastIndexOf('-') + 1);
使用linq似乎也是一個不錯的選擇:
var result = input.Split('>').First().Split('-').Last();
LINQ風格:
var output = input.Split('>').First().Split('-').Last();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.