Formatting a multiline string to be printed on a receipt - c#

I am trying to print a multiline string on a paper from my windows forms application and it does print fine but the formatting is applying only to the first line which is being printed slightly to the right and other lines are being aligned to left for which I would like all the lines to be printed just like the first line
Example
ID : value
Head : value
Hand : value
as you can see from the above ID is printer slightly to the right but head and hand lines are not aligned with the first line
sb.Append(strTempMessage + NEW_LINE);
strTempMessage = AlignNumeric(" ", PAGE_LEFT_MARGIN);
strTempMessage += AlignMessage(strPickSlipNote,0);
sb.Append(strTempMessage + NEW_LINE);
public string AlignMessage(string strMessage, int intBeginningBlankSpace)
{
strMessage = strMessage.Trim();
return AlignNumeric(strMessage, intBeginningBlankSpace);
}
public string AlignNumeric(string strMessage, int intBeginningBlankSpace)
{
intBeginningBlankSpace += strMessage.Length;
if (intBeginningBlankSpace > 0)
return strMessage.PadLeft(intBeginningBlankSpace, ' ');
else
return strMessage;
}
what changes should I make to get all the lines aligned?

I am not too sure if its the most efficient way doing this but you can add tab after appending new line e.g. sb.Append(strTempMessage + NEW_LINE + "\t");

This helped solve
public string FormatPickSlipNoteLines(string input)
{
if (string.IsNullOrEmpty(input))
return "";
else if (input.Length < PAGE_COLUMN_SIZE)
return ALIGN_PAGE_CENTER + input + ALIGN_PAGE_LEFT;
else
{
string[] str = input.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
StringBuilder sbFormatter = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
sbFormatter.Append(" " + str[i] + NEW_LINE);
}
return sbFormatter.Append(NEW_LINE + ALIGN_PAGE_LEFT).ToString();
}
}

Related

Remove characters before character “|”

I have a software which needs to remove all of the characters before "|".
For example input
" text needs to removed | Text needs to stay "
An example output will be
"Text needs to stay"
I have the code down below. It works for single-line text but doesn't work on multiple lines. (only removes the text on the first line rest of them stays the same)
I need to make it work with multiple lines. Any ideas?
string input = richTextBox.Text;
string output = input.Substring(input.IndexOf('|') + 1);
richTextBox1.Text = output;
You could do it easily using the Lines property and a temporary List<string> to store the result of substring
List<string> newLines = new List<string>();
foreach (string s in richTextBox1.Lines)
{
// If you want only the lines with the | remove the else block
int x = s.IndexOf('|');
if(x > -1)
newLines.Add(s.Substring(x + 1).Trim());
else
newLines.Add(s);
}
richTextBox1.Lines = newLines.ToArray();
string output = "";
var myArray = input.Split("\r\n");
foreach(var ar in myArray)
if(ar.Length > 0)
output+= ar.Substring(0, ar.IndexOf('|')) + "\r\n";
Oups! i returned the first part, but i suppose you got the point
What about using LINQ for this.
E.g.:
List<string> lines = yourString.Split("\n"); //Add \r if needed
List<string> smallerLines = lines.Select(x => x.Skip(x.IndexOf('|')+1));
If needed you can always create one new string of the output:
string finalString = String.Join(String.Empty, smallerLines);
string input = richTextBox1.Text;
int len = richTextBox1.Lines.Length;
string output = "";
for (int i = 0; i <len; i++)
{
if(i!=len-1)
{
output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1) +
Environment.NewLine;
}
else
{
output += richTextBox1.Lines[i].Substring(input.IndexOf('|') + 1);
}
}
richTextBox1.Text = output;

Splitting String from Settings

I'm trying to read out the contents off a Setting inside my Application. Below is the code i'm having troubles with:
private bool checkGrid()
{
string playlists = Spotify_Extender.Properties.Settings.Default.Playlists;
MessageBox.Show(playlists);
string[] split1;
if (playlists.Contains(";"))
{
MessageBox.Show("Multiple Links");
split1 = playlists.Split(';');
}
else
{
MessageBox.Show("One Link");
split1 = new string[1];
split1[0] = playlists;
}
MessageBox.Show("Array Length: " + split1.Length);
int lines = 0;
for (int i = 0; i < split1.Length; i++)
{
MessageBox.Show("Check #" + i + " - " + split1[i] + " - Length: " + split1[i].Length);
if (split1[i].Length >= 22)
{
MessageBox.Show(i + " - " + split1[1]);
lines++;
}
}
int rows = this.playlistGrid.Rows.Count;
MessageBox.Show(lines + "");
if (rows == lines)
return true;
return false;
}
The code should be easy to understand and it should work as far as i am aware, but it doesn't. I entered this in my Setting:
If i run the program now, my first MessageBox prints out exactly what i entered, the second one prints out "One Link" and the third prints "Array Length: 1". Now we get to the part i'm having troubles with. The next Message is this:
So the length of the text is 22 as displayed in the MessageBox, but down below this statement isn't true:
if (split1[i].Length >= 22)
I'm really confused by this and it also does this when i check this:
if (split1[i] != "")
Any help is appreciated, because i don't know what to do, since my code should be fine. Thanks for your time!
You should have split[i] and not split[1]

How to parse below string in C#?

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 parse text from richTextBox how can i clear " and , from the string?

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");
}

Split string after certain character count

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))));
}

Categories

Resources