This piece of code is far from perfect, but it works!
It produces a list of substrings (consisting of digits and letters) and their delimiters.
If it is practicaly a sin to manipulate the index of a for loop, then I'm a sinner.
If two delimiters follow each other, an empty string is produced between the two.
If anyone can improve this, please do.
Perhaps solutions with Regex or LINQ are possible.
Or perhaps the great Ketsuekiame can again come up with a one liner? ;)
Splitting a string, delimiters included
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StringSplit
{
class Program
{
static void Main(string[] args)
{
string str = "abc,123.xyz;praise;end,file,clear";
List<string> myText = SplitWithDelimiters(str);
foreach (var item in myText)
{
Console.WriteLine(" item: {0}", item);
}
Console.ReadKey();
}
static List<string> SplitWithDelimiters(string str)
{
List<string> SplittedStringList = new List<string>();
for (int i = 0; i < str.Length; i++)
{
string temp = string.Empty;
int index = i;
bool last = false;
while (char.IsLetterOrDigit(str[index]))
{
temp = temp + str[index];
if (index < str.Length - 1)
{
index++;
}
else
{
last = true;
i = str.Length;
break;
}
}
SplittedStringList.Add(temp);
if (!last)
{
i = index;
SplittedStringList.Add(str[index].ToString());
}
}
return SplittedStringList;
}
}
}
ddanbe 2,724 Professional Procrastinator Featured Poster
kplcjl commented: Unless you are on drugs, that's "busy" learning +3
Ketsuekiame 860 Master Poster Featured Poster
deceptikon 1,790 Code Sniper Team Colleague Featured Poster
kplcjl 17 Junior Poster
kplcjl 17 Junior Poster
kplcjl 17 Junior Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.