どうも、ちょげ(@chogetarou)です。
インデックスを使って文字列(string)の末尾の1文字を取得する方法を紹介します。
方法

インデックスを使って文字列(string)の最後の1文字を取得するには、Lengthを使います。
具体的には、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
コメント