![](/img/trans.png)
[英]Regex to find longest text fragment where last letter of word matches first letter of next word
[英]csharp method word first and last letter
我有方法,其中參數“word”首先返回Word,最后一個字母返回字符串。 在第一個和最后一個字母之間有三個點。 例如,當你編寫“stackoverflow”時,它會像“s ... w”那樣返回它
我有這個代碼,但我不會工作。
namespace stackoverflow
{
class Program
{
static void Main(string[] args)
{
string word = "stackoverflow";
string firsLast = FirsLast(word);
Console.WriteLine(firsLast);
Console.ReadKey();
}
private static string FirsLast(string word)
{
string firsLast = "...";
for (int i = 0; i < word.Length; i += 2)
{
firsLast += word.ElementAt(i);
}
return firsLast;
}
}
}
為什么不
if (word.Length >= 2)
{
return word[0] + "..." + word[word.Length - 1];
}
if (word.Length >= 2)
{
return word.First() + "..." + word.Last();
}
您不需要使用循環來解決這個問題。 重寫您的方法如下:
private static string FirsLast(string word)
{
return word[0] + "..." + word[word.Length - 1];
}
嘗試這個:
private static string FirsLast(string word)
{
string retVal = string.Format("{0}...{1}", word.Substring(0,1), word.Substring(word.Length - 1));
return retVal;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.