search

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 console.writeline>
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534753060561.png?x-oss-process=image/resize,p_40" class="lazy" alt="String Array in C#" ></p>
<ol>
<li>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:</li>
<li>
<strong>Searching in a string array:</strong> 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</li>
</ol>
<p><strong>Example</strong>:</p>
<p><strong>Code:</strong></p>
<pre class="brush:php;toolbar:false">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  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);
}
}
}</string>

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 
<p><strong>Output:</strong></p>
<p><img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534753872074.png?x-oss-process=image/resize,p_40" class="lazy" alt="String Array in C#" ></p><h3 id="Conclusion">Conclusion</h3>
<ol>
<li>String array in C# is used to store multiple strings under a single</li>
<li>The two-dimensional string array is used to represent any matrix kind of</li>
<li>Performance of string array is faster than other collections used to store</li>
<li>They are strongly</li>
</ol>

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
The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

See all articles

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool