我不明白这里的"新字符串"和[i]

  • 本文关键字:字符串 明白 这里 c#
  • 更新时间 :
  • 英文 :


所以我不理解这里的"新字符串"。我试着读了一遍,但找不到任何简单易懂的具体答案。字符串和新字符串之间有什么区别?

public class MainClass {
public static void Main (string[] args) {
Console.Write("nInput number of students: ");
var totalstudents = int.Parse(Console.ReadLine());
var name = new string [totalstudents];
var grade = new int [totalstudents]; 

我的程序无法编译,变成了意外的符号"name"one_answers"grade",我认为这可能与[i]有关,我也不理解。

for (int i =0 ; i<totalstudents ; i++)
{
Console.WriteLine("nInput student name: ")
name[i] = Console.ReadLine(); 
Console.WriteLine("nInput student grade: ")
grade[i] = int.parse(Console.ReadLine());
}
foreach(var gradesof in grade)
{ 
Console.WriteLine(gradesof);
}
}
}
}

string是一个字符串。string[]是字符串的数组,即由可索引字符串元素组成的对象。

string s = "hello"; // Declares and initializes a string.
string[] a = new string[3]; // Declares and initializes a string array of length 3.
// Every element of the array is `null` so far.
// Fill the array with meaningful values.
a[0] = "hello";
a[1] = "world";
a[2] = "!";

您也可以使用数组初始化器来获得相同的结果:

string[] a = new string[] { "hello", "world", "!" };

您可以检索这样的单个元素:

string world = a[1];

使用for:循环通过阵列

for (int i = 0; i < a.Length; i++) {
Console.WriteLine($"a[{i}] = "{a[i]}"");
}

数组可以是任何类型,例如示例中的grade数组是int[]类型。

参见:阵列(C#编程指南(

如注释中所述,new string[...]正在创建一个数组。

您的编译问题包括。。。

线路:

Console.WriteLine("nInput student name: ")
Console.WriteLine("nInput student grade: ")

…在末尾都缺少分号;

还有:

grade[i] = int.parse(Console.ReadLine());

…解析应为Parse

相关内容

最新更新