1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# の string で Python の Slice を実装してみる

1
Last updated at Posted at 2018-07-07

概要

.NET の string.SubString() は、length に文字列の長さ以外を設定するとエラーになったりして、使い勝手が悪いので、Python の スライスと同等の関数を作ってみました。

実装

定義

  public static class StringEx
  {
    /// <summary>
    /// Python の スライスと同じ結果を取得します。
    /// </summary>
    /// <param name="target">このインスタンス。</param>
    /// <param name="startIndex">開始文字位置。</param>
    /// <returns>
    /// このインスタンスの startIndex で始まる部分文字列と等価もしくは取得可能な文字列。
    /// </returns>
    public static string Slice(this string target, int startIndex)
    {
      if (target == null) return "";
      if (target.Length < startIndex) return "";
      return Slice(target, startIndex, target.Length);
    }

    /// <summary>
    /// Python の スライスと同じ結果を取得します。
    /// </summary>
    /// <param name="target">このインスタンス。</param>
    /// <param name="startIndex">開始文字位置。</param>
    /// <param name="endIndex">終了文字位置。</param>
    /// <returns>
    /// このインスタンスの startIndex から endIndex までの部分文字列と等価もしくは取得可能な文字列。
    /// </returns>
    public static string Slice(this string target, int startIndex, int endIndex)
    {
      if (target == null) return "";
      int targetLen = target.Length;
      if (targetLen < startIndex) return "";
      if (startIndex < 0)
      {
        startIndex = targetLen + startIndex;
        if (startIndex < 0) startIndex = 0;
      }
      if (endIndex < 0)
      {
        endIndex = targetLen + endIndex;
        if (endIndex < 0) endIndex = 0;
      }
      if (startIndex >= endIndex)
      {
        return "";
      }
      int len = endIndex > targetLen ? targetLen - startIndex : endIndex - startIndex;
      return target.Substring(startIndex, len);
    }
  }

呼び出し


Console.WriteLine("abcde".Slice(0));   // "abcde"
Console.WriteLine("abcde".Slice(1));   // "bcde"
Console.WriteLine("abcde".Slice(3));   // "de"
Console.WriteLine("abcde".Slice(5));   // ""

Console.WriteLine("abcde".Slice(-1));  // "e"

Console.WriteLine("abcde".Slice(3,4)); // "d"

補足

拡張メソッドを使った実装になります。呼び出し先で StringEx に対して using を記載してください。

編集後記

余裕があれば、Collection 版も作成したい。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?