どうも、ちょげ(@chogetarou)です。
文字列(String)の末尾の1文字を取得する方法を紹介します。
方法

文字列(String)の末尾の1文字を取得する方法は、3つあります。
インデックス
1つ目は、インデックスを使う方法です。
具体的には、str[str.Length - 1]
のように、文字列のLengthプロパティを「−1」したインデックスにアクセスします。
char result = text[text.Length - 1];
Lengthプロパティを−1した値のインデックスにアクセスすることで、文字列の末尾の1文字を取得できます。
使用例
using System;
public class Sample{
public static void Main(){
string text = "Python";
string text2 = "Swift";
string text3 = "Kotlin";
char result = text[text.Length - 1];
char result2 = text2[text2.Length - 1];
char result3 = text3[text3.Length - 1];
System.Console.WriteLine(result);
System.Console.WriteLine(result2);
System.Console.WriteLine(result3);
}
}
出力:
n
t
n
Substring()
2つ目は、Substring()を使う方法です。
まず、文字列からSubstring()を呼び出します。
そして、Substring()の引数に、文字列のLengthプロパティを−1した値を指定します。
string result = text.Substring(text.Length - 1);
上記のSubstring()は、呼び出した文字列の末尾の1文字を取得します。
使用例
using System;
public class Sample{
public static void Main(){
string text = "Python";
string text2 = "Swift";
string text3 = "Kotlin";
string result = text.Substring(text.Length - 1);
string result2 = text2.Substring(text2.Length - 1);
string result3 = text3.Substring(text3.Length - 1);
System.Console.WriteLine(result);
System.Console.WriteLine(result2);
System.Console.WriteLine(result3);
}
}
出力:
n
t
n
System.Linq
3つ目は、System.Linqを使う方法です。
まず、System.Linqを導入します。
using System.Linq;
そして、文字列からLastOrDefault()を呼び出します。
char result = text.LastOrDefault();
上記のLastOrDefault()は、呼び出した文字列の末尾の1文字を取得します。
使用例
using System;
using System.Linq;
public class Sample{
public static void Main(){
string text = "Python";
string text2 = "Swift";
string text3 = "Kotlin";
char result = text.LastOrDefault();
char result2 = text2.LastOrDefault();
char result3 = text3.LastOrDefault();
System.Console.WriteLine(result);
System.Console.WriteLine(result2);
System.Console.WriteLine(result3);
}
}
出力:
n
t
n
まとめ
文字列(string)の最後の1文字を取得する方法は、次の3つです。
- インデックスを使う方法
char result = text[text.Length - 1];
- Substring()を使う方法
string result = text.Substring(text.Length - 1);
- System.Linqを使う方法
char result = text.LastOrDefault();
コメント