0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#のLeft、Right、Mid

Posted at

はじめに

C#にはLeft、Right、Mid関数が無い。
なので、作りました。

基本的にはVB.netの仕様と同じにしています。
※切り出し対象の文字列がnullの場合、VB.netだと空文字を返しますがnullにしています。

サンプル

Left、Right、Mid
/// <summary>
/// 文字列の指定した位置から指定した文字数の文字列を返します
/// </summary>
/// <param name="str">文字列</param>
/// <param name="start">開始位置</param>
/// <param name="length">文字数</param>
/// <returns>取得した文字列</returns>
/// <exception cref="ArgumentException">startが0未満の場合、lengthが0未満の場合</exception>
public static string Mid(string str, int start, int length)
{
    if (start <= 0) throw new ArgumentException("引数'start'は0以上でなければなりません。");
    if (length < 0) throw new ArgumentException("引数'length'は0以上でなければなりません。");
    if (str == null) return null;
    if (length == 0) return string.Empty;
    if (str.Length < start) return string.Empty;
    if (str.Length < start + length) return str.Substring(start - 1);

    return str.Substring(start - 1, length);
}

/// <summary>
/// 文字列の指定した位置から末尾までの文字列を返します
/// </summary>
/// <param name="str">文字列</param>
/// <param name="start">開始位置</param>
/// <returns>取得した文字列</returns>
/// <exception cref="ArgumentException">startが0未満の場合、lengthが0未満の場合</exception>
public static string Mid(string str, int start)
{
    try
    {
        if (str == null) return null;
        return Mid(str, start, str.Length);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

/// <summary>
/// 文字列の先頭から指定した文字数の文字列を返します。
/// </summary>
/// <param name="str">文字列</param>
/// <param name="length">文字数</param>
/// <returns>取得した文字列</returns>
/// <exception cref="ArgumentException">lengthが0未満の場合</exception>
public static string Left(string str, int length)
{
    if (length < 0) throw new ArgumentException("引数'length'は0以上でなければなりません。");
    if (str == null) return null;
    if (length == 0) return string.Empty;
    if (str.Length <= length) return str;

    return str.Substring(0, length);
}

/// <summary>
/// 文字列の末尾から指定した文字数の文字列を返します。
/// </summary>
/// <param name="str">文字列</param>
/// <param name="length">文字数</param>
/// <returns>取得した文字列</returns>
/// <exception cref="ArgumentException">lengthが0未満の場合</exception>
public static string Right(string str, int length)
{
    if (length < 0) throw new ArgumentException("引数'length'は0以上でなければなりません。");
    if (str == null) return null;
    if (length == 0) return string.Empty;
    if (str.Length <= length) return str;

    return str.Substring(str.Length - length, length);
}
0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?