c# string数组

 

 

  • Declaration without size:

    Syntax:

    String[] variable_name;

    or

    string[] variable_name;

  • Declaration with size:

    Syntax:

    String[] variable_name = new String[provide_size_here];

    or

    string[] variable_name = new string[provide_size_here];

    // declaration using string keyword
    string[] s1;

     

    // declaration using String class object
    // by giving its size 4
    String[] s2 = new String[4];

// Declaration of the array
string[] str1, str2;

// Initialization of array
str1 = new string[5]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

str2 = new string[]{ “Element 1”, “Element 2”, “Element 3”, “Element 4”, “Element 5” };

 

// compile-time error: must give size of an array
String[] str = new String[];

// error : wrong initialization of an array
string[] str1;
str1 = {“Element 1”, “Element 2”, “Element 3”, “Element 4” };

 

// declares & initializes string array
String[] s1 = new String[2];

// assign the value "Geeks" in array on its index 0
s1[0] = 10; 

// assign the value "GFG" in array on its index 1
s1[1] = 30;

// assign the value "Noida" in array on its index 2
s1[2] = 20;


// Accessing array elements using index
s1[0];  // returns Geeks
s1[2];  // returns Noida

 

 

   // Main Method

    public static void Main()

    {

        // Step 1: Array Declaration

        string[] stringarr; 

          

        // Step 2:Array Initialization

        stringarr = new string[3] {"Element 1", "Element 2", "Element 3"}; 

          

        // Step 3:Accessing Array Elements

        Console.WriteLine(stringarr[0]); 

        Console.WriteLine(stringarr[1]); 

        Console.WriteLine(stringarr[2]); 

    }

 

 

 // array initialization and declaration

        String[] stringarr = new String[] {"Geeks", "GFG", "Noida"}; 

  

        // accessing array elements

        Console.WriteLine(stringarr[0]);

        Console.WriteLine(stringarr[1]);

        Console.WriteLine(stringarr[2]);

 

 

 

// declaring array of string 

        // using string keyword

        string[] s1 = {"GFG", "Noida"};

  

         // declaring array of string 

        // using String class object

        String[] s2 = new String[2]{"Geeks", "C#"};

  

        // using GetType() method to

        // get type at runtime

        Console.WriteLine(s1.GetType());

        Console.WriteLine(s2.GetType());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值