String Array in C#
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: It is an array of strings. Like a string array of employee names:String: Array of characters.
- It is of fixed
- 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:
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:
- 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:
- 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:
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:
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:
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 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:
- 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.
- 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:
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:
Conclusion
- String array in C# is used to store multiple strings under a single
- The two-dimensional string array is used to represent any matrix kind of
- Performance of string array is faster than other collections used to store
- 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.
