c# - How to convert a string to an int array

Convert a String to an Int Array
The String represents text as a sequence of UTF-16 code units. The String is a sequential collection of characters that is used to represent text. The String is a sequential collection of System.Char objects.

The following .net c# tutorial code demonstrates how we can convert a String object to an Int Array. In this .net c# tutorial code we will initialize a String instance in which content is int values separated by commas. We will split the String object into a String Array then we will create an Int array from this String Array.

The String Split(Char[], StringSplitOptions) method splits a String into substrings based on specified delimiting characters and String split options. Here we will remove empty entries while we split the String instance.

Now, we will call Enumerable Select() method. The Enumerable Select() method projects each element of a sequence into a new form. Using this method, we convert each item into an Int instance. Then, we convert this enumerable to an Array. In this way, we convert a String object to an Int array instance. The Enumerable ToArray() method creates an Array from an IEnumerable<T>.

<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>    
<script runat="server">  
    protected void Button1_Click(object sender, System.EventArgs e)
        //this line create a string variable.
        string stringOfInteger = "1,5,10,15,,,20,25,30";

        Label1.Text = "string of ip integer value............<br />";
        Label1.Text += stringOfInteger;

        //split string and create an integer data type array.
        int[] intArray = stringOfInteger.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

        Label1.Text += "<br /><br />elements of int array............<br />";
        foreach (int i in intArray)
            Label1.Text += "<br />"+i;
<html xmlns="http://www.w3.org/1999/xhtml">    
<head id="Head1" runat="server">    
    <title>c# example - string to int array</title>    
    <form id="form1" runat="server">    
        <h2 style="color:MidnightBlue; font-style:italic;">    
            c# example - string to int array
        <hr width="550" align="left" color="Gainsboro" />    
        <br /><br />  
            Text="string to int array"    
More c# examples