最初の質問
使用できますString.SubString()
:
string a = "I once was a string, then I got mutilated";
string lastTwentyCharactersOfA = a.Substring(Math.Max(0, a.Length - 20));
// returns "then I got mutilated"
クレジットが必要な場合のクレジット: この回答は、文字列の文字数が要求した文字数よりも少ない場合に例外が発生しないようにする優れた仕事をします。
2 番目の質問
使用できますString.Contains()
:
string soup = "chicken noodle soup";
bool soupContainsChicken = soup.Contains("chicken"); // returns True
3 番目の質問
String
クラスの乗算演算子をオーバーライドすることはできません。これは封印されたクラスであり、もちろん、ソース コードにアクセスしてクラスなどにすることはできませんpartial
。やりたいことに近づけるオプションがいくつかあります。1 つは、拡張メソッドを作成することです。
public static string MultiplyBy(this string s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s);
}
return sb.ToString();
}
使用法:
string lol = "lol";
string trololol = lol.MultiplyBy(5); // returns "lollollollollol"
または、演算子のオーバーロードのルートに進みたい場合は、カスタムString
クラスの並べ替えを作成してから使用できます。
public struct BetterString // probably not better than System.String at all
{
public string Value { get; set; }
public static BetterString operator *(BetterString s, int times)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < times; i++)
{
sb.Append(s.Value);
}
return new BetterString { Value = sb.ToString() };
}
}
使用法:
BetterString lol = new BetterString { Value = "lol" };
BetterString trololol = lol * 5; // trololol.Value is "lollollollollol"
一般に、 と でできることはたくさんSystem.String
ありますSystem.Text.StringBuilder
。そして、拡張メソッドの可能性はほぼ無限です。すべての詳細を知りたい場合は、MSDN を調べてください。