views:

1279

answers:

2

I want to create an array/list of strings of the Comma seperated strings (file extensions) that are entered in a Textbox.

For the following block of code:

            Dim csv As String = Textbox1.Text + ","

            While csv.IndexOf(".") <> -1
                lstOfStrings.Add(csv.Substring(0, csv.IndexOf(",")))
                csv = csv.Remove(0, csv.IndexOf(",") + 1)
            End While

The output is:

Textbox1.Text = ".exe,.php"

listOfStrings = { ".exe", ".php" }

Is there a better way to write this code?

+5  A: 

A better way would be to use the Split method:

Dim lstOfStrings() As String = Textbox1.Text.Split(","c)
Darin Dimitrov
Thank you!Also, is a List "lighter" than an Array of strings?
A list of strings uses internally an array of strings for storage, so an array is lighter, but with fixed size. You can add elements to the list and it will dynamically resize if the internal array cannot hold the new data.
Darin Dimitrov
No, a List is slightly heavier than an Array, but the difference will be insignificant for a typical GUI program.
ggf31416
Also, to create a list (which is 'heavier') if you need one, simply call it's constructor with the array as a parameter: Dim lstOfStrings As List(Of String) = New List(Of String)(Textbox1.Text.Split(","c)) - hope I got the VB syntax right.
configurator
+1  A: 

Here is a different way with Regex+LINQ. It allows for whole file names, if thats something you value. Split is preferable depending on how conditioned the input is (spaces and the like).

using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "fileone.aspx, filetwo.csv,filethree.exe, filefour.php";
            List<string> extensions = Regex.Matches(s, @"(\.\w+)\s*,?")
                .OfType<Match>().Select(m => m.Groups[1].Value)
                .ToList();
            extensions.ForEach(i => Console.WriteLine(i));
            Console.ReadLine();
        }
    }
}

OUTPUT

.aspx

.csv

.exe

AFTERTHOUGHT

You could add .Distinct() if you wanted unique extensions

ccook