Table of Contents
Declaration Syntax
Initialization of string array
Assigning Values
Examples of String Array in C#
1. Accessing array elements using the index number
2. Accessing array elements using for loop
String array and list of strings
2D string array
Conclusion

String Array in C#

Sep 03, 2024 pm 03:12 PM
c# c# tutorial

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];
Copy after login

By using a string keyword:

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

2. Declaration without size

String[] variable_name;
Copy after login
string[] variable_name;
Copy after login

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>];
Copy after login
Copy after login

2. After declaration:

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

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"};
Copy after login

OR

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

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]);
}
}
Copy after login

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]);
}
}
}
Copy after login

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);
}
}
}
Copy after login

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);
}
}
}
Copy after login

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);
}
}
}
Copy after login

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);
}
}
}
Copy after login

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);
}
}
}
Copy after login

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);
}
}
}
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

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

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

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

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

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

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

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.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

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 c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

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.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

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.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

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

See all articles