Please someone to help me to parse these sample string below? I'm having difficulty to split the data and also the data need to add carriage return at the end of every event
sample string:
L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00
batch of events
expected output:
L,030216,182748,00,FF,I,00 - 1st Event
L,030216,182749,00,FF,I,00 - 2nd Event
L,030216,182750,00,FF,I,00 - 3rd Event
Seems like an easy problem. Something as easy as this should do it:
string line = "L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00";
string[] array = line.Split(',');
StringBuilder sb = new StringBuilder();
for(int i=0; i<array.Length-1;i+=6)
{
sb.AppendLine(string.Format("{0},{1} - {2} event",array[0],string.Join(",",array.Skip(i+1).Take(6)), "number"));
}
output (sb.ToString()):
L,030216,182748,00,FF,I,00 - number event
L,030216,182749,00,FF,I,00 - number event
L,030216,182750,00,FF,I,00 - number event
All you have to do is work on the function that increments the ordinals (1st, 2nd, etc), but that's easy to get.
This should do the trick, given there are no more L's inside your string, and the comma place is always the sixth starting from the beginning of the batch number.
class Program
{
static void Main(string[] args)
{
String batchOfevents = "L,030216,182748,00,FF,I,00,030216,182749,00,FF,I,00,030216,182750,00,FF,I,00,030216,182751,00,FF,I,00,030216,182752,00,FF,I,00,030216,182753,00,FF,I,00";
// take out the "L," to start processing by finding the index of the correct comma to slice.
batchOfevents = batchOfevents.Substring(2);
String output = "";
int index = 0;
int counter = 0;
while (GetNthIndex(batchOfevents, ',', 6) != -1)
{
counter++;
if (counter == 1){
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - 1st event\n";
batchOfevents = batchOfevents.Substring(index + 1);
} else if (counter == 2) {
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - 2nd event\n";
batchOfevents = batchOfevents.Substring(index + 1);
}
else if (counter == 3)
{
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - 3rd event\n";
batchOfevents = batchOfevents.Substring(index + 1);
} else {
index = GetNthIndex(batchOfevents, ',', 6);
output += "L, " + batchOfevents.Substring(0, index) + " - " + counter + "th event\n";
batchOfevents = batchOfevents.Substring(index + 1);
}
}
output += "L, " + batchOfevents + " - " + (counter+1) + "th event\n";
Console.WriteLine(output);
}
public static int GetNthIndex(string s, char t, int n)
{
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == t)
{
count++;
if (count == n)
{
return i;
}
}
}
return -1;
}
}
Now the output will be in the format you asked for, and the original string has been decomposed.
NOTE: the getNthIndex method was taken from this old post.
If you want to split the string into multiple strings, you need a set of rules,
which are implementable. In your case i would start splitting the complete
string by the given comma , and than go though the elements in a loop.
All the strings in the loop will be appended in a StringBuilder. If your ruleset
say you need a new line, just add it via yourBuilder.Append('\r\n') or use AppendLine.
EDIT
Using this method, you can also easily add new chars like L or at the end rd Event
Look for the start index of 00,FF,I,00 in the entire string.
Extract a sub string starting at 0 and index plus 10 which is the length of the characters in 1.
Loop through it again each time with a new start index where you left of in 2.
Add a new line character each time.
Have a try the following:
string stream = "L,030216,182748,00,FF,I,00, 030216,182749,00,FF,I,00, 030216,182750,00,FF,I,00";
string[] lines = SplitLines(stream, "L", "I", ",");
Here the SplitLines function is implemented to detect variable-length events within the arbitrary-formatted stream:
string stream = "A;030216;182748 ;00;FF;AA;01; 030216;182749;AA;02";
string[] lines = SplitLines(batch, "A", "AA", ";");
Split-rules are:
- all elements of input stream are separated by separator(, for example).
- each event is bounded by the special markers(L and I for example)
- end marker is previous element of event-sequence
static string[] SplitLines(string stream, string startSeq, string endLine, string separator) {
string[] elements = stream.Split(new string[] { separator }, StringSplitOptions.RemoveEmptyEntries);
int pos = 0;
List<string> line = new List<string>();
List<string> lines = new List<string>();
State state = State.SeqStart;
while(pos < elements.Length) {
string current = elements[pos].Trim();
switch(state) {
case State.SeqStart:
if(current == startSeq)
state = State.LineStart;
continue;
case State.LineStart:
if(++pos < elements.Length) {
line.Add(startSeq);
state = State.Line;
}
continue;
case State.Line:
if(current == endLine)
state = State.LineEnd;
else
line.Add(current);
pos++;
continue;
case State.LineEnd:
line.Add(endLine);
line.Add(current);
lines.Add(string.Join(separator, line));
line.Clear();
state = State.LineStart;
continue;
}
}
return lines.ToArray();
}
enum State { SeqStart, LineStart, Line, LineEnd };
f you want to split the string into multiple strings, you need a set of rules, which are implementable. In your case i would start splitting the complete string by the given comma , and than go though the elements in a loop. All the strings in the loop will be appended in a StringBuilder. If your ruleset say you need a new line, just add it via yourBuilder.Append('\r\n') or use AppendLine.
I like to delete last line of richtextbox which has ended with ; semicolumn. I like to delete this line until ; semicolumn that comes before the last semicolumn.
Example:
hello do not delete this line;
hello this sentence will continue...
untill here;
result should be:
hello do not delete this line;
My Code:
private void button1_Click_1(object sender, EventArgs e) {
List<string> myList = richTextBox1.Lines.ToList();
if (myList.Count > 0) {
myList.RemoveAt(myList.Count - 1);
richTextBox1.Lines = myList.ToArray();
richTextBox1.Refresh();
}
}
Found the solution here:
RichTextBox1.Lines = RichTextBox1.Lines.Take(RichTextBox1.Lines.Length - 3).ToArray();
Use this:
var last = richTextBox1.Text.LastIndexOf(";");
if (last > 0)
{
richTextBox1.Text = richTextBox1.Text.Substring(0, last - 1);
var beforelast = richTextBox1.Text.LastIndexOf(";");
richTextBox1.Text = richTextBox1.Text.Substring(0, beforelast + 1);
}
else
{
richTextBox1.Text = "";
}
You did not specify the other scenarios(i.e, when the string does not contain ";")
this code removes the string starting at ";" just before the last ";" to the last ";".
It removes the last semicolon and texts after that, then finds the new last ";". finally removes the text after this ";"
For those that find this question after all these years...
The solutions that use the .Text property or .Lines property end up removing the formatting from the existing text. Instead use something like this to preserve formatting:
var i = textBox.Text.LastIndexOf("\n");
textBox.SelectionStart = i;
textBox.SelectionLength = o.TextLength - i + 1;
textBox.SelectedText = "";
Note that if your textbox is in ReadOnly mode, you can't modify SelectedText. In that case you need to set and reset ReadOnly like this:
textBox.ReadOnly = false;
textBox.SelectedText = "";
textBox.ReadOnly = true;
I'm not sure exactly how the rich text box works, but something like
input = {rich text box text}
int index = text.lastIndexOf(";");
if (index > 0)
{
input = input.Substring(0, index);
}
// put input back in text box
How about that ?
string input = "your complete string; Containing two sentences";
List<string> sentences = s.Split(';').ToList();
//Delete the last sentence
sentences.Remove(sentences[sentences.Count - 1]);
string result = string.Join(" ", sentences.ToArray());
int totalcharacters = yourrtb.Text.Trim().Length;
int totalLines = yourrtb.Lines.Length;
string lastLine = yourrtb.Lines[totalLines - 1];
int lastlinecharacters = lastLine.Trim().Length;
yourrtb.Text = yourrtb.Text.Substring(0, totalcharacters - lastlinecharacters);
This is the code:
public static string ParseText(string text, int startPos, int endPos)
{
string images = "";
if (startPos >= 0 && endPos > startPos)
{
images = text.Substring(startPos + 1, endPos - startPos - 1);
images.Replace(',',' ');
}
return images;
}
Im using this part to clean/remove , and "
entries = images.Split(new[] { ',' });
for (var i = 0; i < entries.Length; i++)
{
entries[i] = entries[i].Replace("\"", "");
}
For example if i have this part of text:
"http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311221800&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311222100&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230000&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230300&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230600&cultuur=en-GB&continent=europa","http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311230900&cultuur=en-GB&continent=europa","
And its longer...But in this example i want to remove all the " and ,
If im using the code as it is now the result is:
Im getting only the first link:
http://www.niederschlagsradar.de/images.aspx?jaar=-6&type=europa.cld&datum=201311221800&cultuur=en-GB&continent=europa
If i remove the lines:
entries = images.Split(new[] { ',' });
for (var i = 0; i < entries.Length; i++)
entries[i] = entries[i].Replace("\"", "");
Then i will see all the text but with , and "
What is wrong with cleaning the , and "?
Why it show me only the first text part and not all the rest ?
strings in C# are immutable.
images.Replace(',', '');
... by design does not affect images. What you need is:
images = images.Replace(',', ' ');
Perhaps you want them as a joined string?
var result = string.Join(Environment.NewLine, images.Split(new[] { ',' }).Select(e => e.Replace("\"", "")));
If I'm understanding your comment correctly,
// could easily be an extension method
public static string ReplacingChars(string source, char[] toReplace, string withThis)
{
return string.Join(withThis, source.Split(toReplace, StringSplitOptions.None));
}
// usage:
images = ReplacingChars(images, new [] {',', '"'}, " ");
Try using string.Replace(). See MSDN for more information.
e.g.
images.Replace(',','');
The following works for me!
string ParseText(string input)
{
// Replace quotes with nothing at all...
var noQuotes = input.Replace("\"", "");
// Replace commas with, I dunno, "whatever you want"...
// If you want to just get rid of the commas, you could use "",
// or if you want a space, " "
return input.Replace("," "whatever you want");
}
I need some help. I'm writing an error log using text file with exception details. With that I want my stack trace details to be written like the below and not in straight line to avoid the user from scrolling the scroll bar of the note pad or let's say on the 100th character the strings will be written to the next line. I don't know how to achieve that. Thanks in advance.
SAMPLE(THIS IS MY CURRENT OUTPUT ALL IN STRAIGHT LINE)
STACKTRACE:
at stacktraceabcdefghijklmnopqrstuvwxyztacktraceabcdefghijklmnopqrswxyztacktraceabcdefghijk
**MY DESIRED OUTPUT (the string will write to the next line after certain character count)
STACKTRACE:
at stacktraceabcdefghijklmno
pqrstuvwxyztacktraceabcdefgh
ijklmnopqrswxyztacktraceabcd
efghijk
MY CODE
builder.Append(String.Format("STACKTRACE:"));
builder.AppendLine();
builder.Append(logDetails.StackTrace);
Following example splits 10 characters per line, you can change as you like {N} where N can be any number.
var input = "stacktraceabcdefghijklmnopqrstuvwxyztacktraceabcdefghijklmnopqrswxyztacktraceabcdefghijk";
var regex = new Regex(#".{10}");
string result = regex.Replace(input, "$&" + Environment.NewLine);
Console.WriteLine(result);
Here is the Demo
you can use the following code:
string yourstring;
StringBuilder sb = new StringBuilder();
for(int i=0;i<yourstring.length;++i){
if(i%100==0){
sb.AppendLine();
}
sb.Append(yourstring[i]);
}
you may create a function for this
string splitat(string line, int charcount)
{
string toren = "";
if (charcount>=line.Length)
{
return line;
}
int totalchars = line.Length;
int loopcnt = totalchars / charcount;
int appended = 0;
for (int i = 0; i < loopcnt; i++)
{
toren += line.Substring(appended, charcount) + Environment.NewLine;
appended += charcount;
int left = totalchars - appended;
if (left>0)
{
if (left>charcount)
{
continue;
}
else
{
toren += line.Substring(appended, left) + Environment.NewLine;
}
}
}
return toren;
}
Best , Easiest and Generic Answer :). Just set the value of splitAt to the that number of character count after that u want it to break.
string originalString = "1111222233334444";
List<string> test = new List<string>();
int splitAt = 4; // change 4 with the size of strings you want.
for (int i = 0; i < originalString.Length; i = i + splitAt)
{
if (originalString.Length - i >= splitAt)
test.Add(originalString.Substring(i, splitAt));
else
test.Add(originalString.Substring(i,((originalString.Length - i))));
}