Home  >  Article  >  Backend Development  >  String Array in C#

String Array in C#

WBOY
WBOYOriginal
2024-09-03 15:12:04641browse

To understand String Array in C#, let us first understand what is an array and string.

Array: A collection of the same type of variables stored sequentially and each variable can be accessed using its index number. Indexing an array starts with zero.

For example an array of five integers

String Array in C#

String Array: It is an array of strings. Like a string array of employee names:String: Array of characters.

String Array in C#

  1. It is of fixed
  2. It can be single or multi

Declaration Syntax

There are two ways to declare a string array:

1. Declaration with size

By using the String class object:

String[] variable_name = new String[size];

By using a string keyword:

string[] <em>variable_name </em>= new string[<em>size</em>];

2. Declaration without size

String[] variable_name;
string[] variable_name;

Initialization of string array

String array can be initialized using the new keyword. We cannot initialize string array without specifying it’s the size. There are two ways to initialize a string array.

1. At the time of declaration:

string[] <em>variable_name </em>= new string[<em>size</em>];

2. After declaration:

string [] <em>variable_name</em>; 
<em>variable_name </em>= new string[<em>size</em>];

Assigning Values

Values to string array can be assigned at the time of initialization or by using index number.

Example:

string[] stringer = new stringArr[3]{"value1","value2","value3"};

OR

string[] stringArr = new stringArr[3]; 
stringArr[0] = "value1";
stringArr[1] = "value2"; 
stringArr[2] = "value3";

Examples of String Array in C#

Some of the examples are given below:

1. Accessing array elements using the index number

Code:

using System;
public class StringArray
{
public static void Main()
{
// Array Declaration and Initialization
string[] stringArr = new string[3] {"value1", "value2", "value3"};
// Accessing elements using index
Console.WriteLine(stringArr[0]);
Console.WriteLine(stringArr[1]);
Console.WriteLine(stringArr[2]);
}
}

Output:

String Array in C#

2. Accessing array elements using for loop

Code:

using System;
public class StringArray
{
public static void Main()
{
// Array Declaration and Initialization
string[] stringArr= new string[3] {"element1", "element2", "element3"};
// Accessing elements using for loop
for(int i=0;i<stringArr.Length;i++)
{
Console.WriteLine(stringArr[i]);
}
}
}

Output:

String Array in C#

  1. Apart from this, we can perform many operations on string arrays like searching, sorting, converting string array to string or converting string to string array and many more. Let us see some of these operations in examples below:
  2. Searching in a string array: There are many ways to search for a word or we can say for a string in the string array. One is using the Find() method of Array class. This method returns the first element in the array that matches the conditions defined by the specified predicate

Example:

Code:

using System;
public class StringSearch
{
public static void Main()
{
try {
// Creating and initializing string array of flower names
String[] flowerArr = new String[]{"Lily", "Jasmine", "Rose", "Sunflower"};
// Print values of the string array
Console.WriteLine("Flower names:");
for (int i = 0; i < flowerArr.Length; i++)
{
Console.WriteLine("{0}", flowerArr[i]);
}
Console.WriteLine();
//Search for flower name that starts with 'R'
string result = Array.Find(flowerArr, name => name.StartsWith("R", StringComparison.CurrentCultureIgnoreCase));
//Print result
Console.Write("Flower name starting with 'R': {0}", result);
}
catch (Exception e)
{
Console.Write("{0}", e.Message);
}
}
}

Output:

String Array in C#

Sorting in a string array: We can sort a string array in many ways. Here we will sort it using Array.Sort()

Example:

Code:

using System;
public class StringSort
{
public static void Main()
{
try
{
// declaring and initializing string array
String[] stringArr = new String[] {"Cat", "Creature", "Culture", "Cow"};
// Sorting in ascending order.
Array.Sort(stringArr);
// reverse array to sort it in descending order
Array.Reverse(stringArr);
// print sorted array
foreach(string val in stringArr)
{
Console.Write(val + " ");
}
}
catch(Exception ex)
{
Console.Write(ex.Message);
}
}
}

Output:

String Array in C#

Converting string to string array: We can easily convert a string to a string array and vice versa as shown in the below examples:

Example:

Code:

using System;
public class StringToStringArray { public static void Main()
{
try
{
string str = "Hello world";
//convert string to string array
string[] strArr = new string[]{ str };
//print string array
foreach(string s in strArr)
{
Console.Write(s);
}
}
catch(Exception ex)
{
Console.Write(ex.Message);
}
}
}

Output:

String Array in C#

The output displayed is not a string but a string array. Example converting string array to string:

using System;
public class StringArrayToString { public static void Main()
{
try{
}
string[] strArr = new string[2]; strArr[0] = "Good";
strArr[1] = "Morning!";
//converting string array to string
string str = string.Join("", strArr);
//print string
Console.WriteLine(str);
catch(Exception ex)
{
Console.Write(ex.Message);
}
}
}

Output:

 String Array in C#

String array and list of strings

From the above examples, we can say that a string array is very much similar to a list of string. But here are two major differences between them:

  1. We cannot resize string array e. if you have a string array of size four, then you cannot add five elements in it. On the other hand, the list can be resized any time, you can add as many elements as you want in a list.
  2. The list is slower than the array, thus operations performed on string array will be faster than that of

We can convert a string array to list as shown below:

using System;
using System.Collections.Generic;
using System. Linq;
public class StringArrayToList
{
public static void Main()
{
string[] strArray = new string[]{ "string", "array", "to", "list"};
//converting string array to list
List<string> list = strArray.ToList();
//print list
foreach (string item in the list)
{
Console.WriteLine(item);
}
}
}

Output:

 String Array in C#

2D string array

C# also supports multidimensional string array, the simplest form of a multidimensional string array is 2D string array.

Example:

Code:

using System;
public class TwoDimensionalArray
{
public static void Main()
{
string[,] strArr = new string[,]
{
{"Twenty", "Forty"},
{"Thirty", "Fifty"}
};
for (int i = 0; i <= strArr.GetUpperBound(0); i++)
{
string s1 = strArr[i, 0]; string s2 = strArr[i, 1];
Console.WriteLine("{0}, {1}", s1, s2);
}
}
}

Output:

String Array in C#

Conclusion

  1. String array in C# is used to store multiple strings under a single
  2. The two-dimensional string array is used to represent any matrix kind of
  3. Performance of string array is faster than other collections used to store
  4. They are strongly

The above is the detailed content of String Array in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# Jagged ArraysNext article:C# Jagged Arrays