要从字符串访问元素/字符,我们使用String.Chars []属性,就像C,C ++和其他编程语言一样–我们可以从指定的索引访问字符串的字符。
语法:
public char this[int index] { get; }
参数: index是必须访问字符的位置,索引的最小值为0,最大值为length-1。
返回值: char –返回一个字符。
示例
Input: string str = "nhooo"; accessing characters: str[0]: 'I' str[1]: 'n' str[str.Lenght-1]: 'p'
using System; using System.Text; namespace Test { class Program { static void Main(string[] args) { //字符串变量声明 string str = "nhooo"; //打印第一个和最后一个字符 Console.WriteLine("First character is: " + str[0]); Console.WriteLine("Last character is: " + str[str.Length-1]); //根据索引打印所有字符 for (int loop = 0; loop < str.Length; loop++) { Console.WriteLine("character at {0} index is = {1}", loop, str[loop]); } //按ENTER退出 Console.ReadLine(); } } }
输出结果
First character is: I Last character is: p character at 0 index is = I character at 1 index is = n character at 2 index is = c character at 3 index is = l character at 4 index is = u character at 5 index is = d character at 6 index is = e character at 7 index is = H character at 8 index is = e character at 9 index is = l character at 10 index is = p
参考:String.Chars [Int32]属性