C# string parsing question - c#

I'm trying to split a string:
string f = r.ReadToEnd();
string[] seperators = new string[] {"[==========]"};
string[] result;
result = f.Split(seperators, StringSplitOptions.None);
There's this ========== thing that separates entries. For the life of me, I can't get this to work. I've got a ruby version working...BUT using the string splitter classes I thought I knew for .NET doesn't seem to be working so well.
Any ideas what I'm doing wrong?

You said that the separator is ========== but you're using [==========]. Try this:
string f = r.ReadToEnd();
string[] seperators = new string[] {"=========="};
string[] result;
result = f.Split(seperators, StringSplitOptions.None);

When I ran your code with the following modification:
string f = "string1[==========]string2[==========]string3";
string[] seperators = new string[] { "[==========]" };
string[] result;
result = f.Split(seperators, StringSplitOptions.None);
foreach (string x in result) Console.WriteLine(x);
The function writes out the strings as expected. I'd look at the contents of your file more closely - perhaps there is something in the encoding, or some other character that is missing when you devise a separator to work in C#/Windows.

Related

Get a string inside a string

string a = "100-0-6-7-6-10-8-" //and so on
/////////////////////////////////////////////
//my solution
char[] delimiterChars = {'-'};
string solution = "100-0-6-7-6-10-8-";
string[] words = solution.Split(delimiterChars,System.StringSplitOptions.RemoveEmptyEntries);
//ok so i encounter some problems when trying to overwrite 0s, and 10s,100s etc
//so when writing data to the "solution" string it should be
//"-100--0--6--7--6--10--8-" instead of "100-0-6-7-6-10-8-"
basically, I want to separate each number and put it in a list or array
i think i got it
char[] delimiterChars = {'-'};
string text = "100-0-6-7-6-10-8-";
string[] words = text.Split(delimiterChars,System.StringSplitOptions.RemoveEmptyEntries);
This solution using Linq works as well.
var text="100-0-6-7-6-10-8-";
var words=text.Split("-").Where(x => !string.IsNullOrEmpty(x)).ToArray();

Unable to split a string using split() method

I have a string
String data="CE|2014-2015|ClassA"
I need output like
string Batch="2014-2015"
string Class="ClassA"
How can I achieve it?? I tried a lot string,Split() function. But I did not get expected output.Please help me out
I tried,
string s = "CE|2014-2015|Class1";
string[] words = s.Split('|| ');
This should work for you
string[] splitted = data.Split('|');
string Batch = splitted[1];
string Class = splitted[2];
Your solution is wrong because: '|| ' is not a valid char and it won't even compile. You should split on | and take second and third value from splitted values
You can do the following
string data = "CE|2014-2015|ClassA";
string[] split = data.Split('|');
string Batch=split[1];
string Class = split[2];
Hope it works for you.

How to get the next word in a string?

I feel pretty foolish for asking a seemingly easy question Sigh but for the life of me I cant figure it out.
string myString = "10/27/14 TheNextString DontWantThisString";
Assume that the second string is unknown(as in it could be any type of word). How could I get the second word after the last index of the date.
Sorry this Is probably a weird question.
var lastLine = line.Substring(idx + "date:".Length + 1, 14);
var lastChar = lastLine.Substring(lastLine.Length-1, 1);
headerName = lastLine.Substring(lastLine.LastIndexOf(lastChar), +1);
Heres some of my code for a little context if you will.
You want String.Split().
string[] delimiters = new string[] {" "};
string[] words = myString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
string myString = "10/27/14 TheNextString DontWantThisString";
var values = Regex.Split(myString , #"\s+");
if (values.Count > 1)
Console.WriteLine(values[1]);
This should work (haven't tested the code, but you get the idea).
String result[] = myString.split(null);
result[1] will return what you need.
See: String.SplitMethod
namespace SplitDemo
{
class Program
{
static void Main(string[] args)
{
var myString = "10/27/14 TheNextString DontWantThisString";
var stringArray = myString.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries);
var word = stringArray[1];
}
}
}
Something like this should work for you. This splits the string into an array, using a space as the separator, removes any empty matches, and then gets the second item.
myString.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)[1]
http://msdn.microsoft.com/en-us/library/ms131448.aspx

Using RemoveEmptryEntries with .Split in C#

I have a string that's using semicolons as the delimitor. I drop them into a List of strings, and I want it to ignore Empty entries, but the option is throwing an error when I include it. The working code looks like so:
tContent = (HtmlInputText)FindControl("SomeInput");
string tText = tContent.Value;
List<string> tTextList = tText.Split(';').ToList();
To get rid of extra blank entries, I tried to employ this:
tContent = (HtmlInputText)FindControl("SomeInput");
string tText = tContent.Value;
List<string> tTextList = tText.Split(';', StringSplitOptions.RemoveEmptyEntries).ToList();
But it comes back with an error that it contains invalid arguments. My best efforts seem to indicate that this should be valid, but the compiler disagrees. I suspect a very silly error and I'm just in need of a second set of eyes in this case.
Change
List<string> tTextList = tText.Split(';', StringSplitOptions.RemoveEmptyEntries).ToList();
to
List<string> tTextList = tText.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
You can see the supported signatures for string.Split here: http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
You need a char array:
List<string> tTextList = tText.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries).ToList();

C#: Getting Substring between two different Delimiters

I have problems splitting this Line. I want to get each String between "#VAR;" and "#ENDVAR;". So at the End, there should be a output of:
Variable=Speed;Value=Fast;
Variable=Fabricator;Value=Freescale;Op==;
Later I will separate each Substring, using ";" as a delimiter but that I guess wont be that hard. This is how a line looks like:
#VAR;Variable=Speed;Value=Fast;Op==;#ENDVAR;#VAR;Variable=Fabricator;Value=Freescale;Op==;#ENDVAR;
I tried some split-options, but most of the time I just get an empty string. I also tried a Regex. But either the Regex was wrong or it wasnt suitable to my String. Probably its wrong, at school we learnt Regex different then its used in C#, so I was confused while implementing.
Regex.Match(t, #"/#VAR([a-z=a-z]*)/#ENDVAR")
Edit:
One small question: I am iterating over many lines like the one in the question. I use NoIdeas code on the line to get it in shape. The next step would be to print it as a Text-File. To print an Array I would have to loop over it. But in every iteration, when I get a new line, I overwrite the Array with the current splitted string. I put the Rest of my code in the question, would be nice if someone could help me.
string[] w ;
foreach (EA.Element theObjects in myPackageObject.Elements)
{
theObjects.Type = "Object";
foreach (EA.Element theElements in PackageHW.Elements)
{
if (theObjects.ClassfierID == theElements.ElementID)
{
t = theObjects.RunState;
w = t.Replace("#ENDVAR;", "#VAR;").Replace("#VAR;", ";").Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in w)
{
tw2.WriteLine(s);
}
}
}
}
The piece with the foreach-loop is wrong pretty sure. I need something to print each splitted t. Thanks in advance.
you can do it without regex using
str.Replace("#ENDVAR;", "#VAR;")
.Split(new string[] { "#VAR;" }, StringSplitOptions.RemoveEmptyEntries);
and if you want to save time you can do:
str.Replace("#ENDVAR;", "#VAR;")
.Replace("#VAR;", ";")
.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
You can use a look ahead assertion here.
#VAR;(.*?)(?=#ENDVAR)
If your string never consists of whitespace between #VAR; and #ENDVAR; you could use the below line, this will not match empty instances of your lines.
#VAR;([^\s]+)(?=#ENDVAR)
See this demo
Answer using raw string manipulation.
IEnumerable<string> StuffFoundInside(string biggerString)
{
var closeDelimeterIndex = 0;
do
{
int openDelimeterIndex = biggerString.IndexOf("#VAR;", startingIndex);
if (openDelimeterIndex != -1)
{
closeDelimeterIndex = biggerString.IndexOf("#ENDVAR;", openDelimeterIndex);
if (closeDelimiterIndex != -1)
{
yield return biggerString.Substring(openDelimeterIndex, closeDelimeterIndex - openDelimiterIndex);
}
}
} while (closeDelimeterIndex != -1);
}
Making a list and adding each item to the list then returning the list might be faster, depending on how the code using this code would work. This allows it to terminate early, but has the coroutine overhead.
Use this regex:
(?i)#VAR;(.+?)#ENDVAR;
Group 1 in each match will be your line content.
(If you don't like regexs)
Code:
var s = "#VAR;Variable=Speed;Value=Fast;Op==;#ENDVAR;#VAR;Variable=Fabricator;Value=Freescale;Op==;#ENDVAR;";
var tokens = s.Split(new String [] {"#ENDVAR;#VAR;"}, StringSplitOptions.None);
foreach (var t in tokens)
{
var st = t.Replace("#VAR;", "").Replace("#ENDVAR;", "");
Console.WriteLine(st);
}
Output:
Variable=Speed;Value=Fast;Op==;
Variable=Fabricator;Value=Freescale;Op==;
Regex.Split works well but yields empty entries that have to be removed as shown here:
string[] result = Regex.Split(input, #"#\w+;")
.Where(s => s != "")
.ToArray();
I tried some split-options, but most of the time I just get an empty string.
In this case the requirements seem to be simpler than you're stating. Simply splitting and using linq will do your whole operation in one statement:
string test = "#VAR;Variable=Speed;Value=Fast;Op==;#ENDVAR;#VAR;Variable=Fabricator;Value=Freescale;Op==;#ENDVAR;";
List<List<string>> strings = (from s in test.Split(new string[]{"#VAR;",";#ENDVAR;"},StringSplitOptions.RemoveEmptyEntries)
let s1 = s.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries).ToList<string>()
select (s1)).ToList<List<string>>();
the outpout is:
?strings[0]
Count = 3
[0]: "Variable=Speed"
[1]: "Value=Fast"
[2]: "Op=="
?strings[1]
Count = 3
[0]: "Variable=Fabricator"
[1]: "Value=Freescale"
[2]: "Op=="
To write the data to a file something like this will work:
foreach (List<string> s in strings)
{
System.IO.File.AppendAllLines("textfile1.txt", s);
}

Categories

Resources