I'm trying to split a string that represents a filepath, so the path contains pictures. For example should the pathstring #c:\users\common\pictures\2008 be converted to pictures\2008. The problem that I encounter is that when I use \ in a string it gives me an error. Sorry for the dumb question, m new with C#. This is what I've done so far:
string path = "#c:\users\common\pictures\2008";
string[] subs = path.Split('\');
int count = 0;
while(subs[count] != "pictures")
{
count++;
}
string newPath = "";
for (int i = count; i < subs.Length; i++)
{
newPath += "\" + subs[i];
}
Console.WriteLine(newPath);
That's because \ is a reserved char in C# so you must use it in this way '\\'
In case of string you can add before the special char #
In case of char you have to double it \\
See the documentation
string path = #"#c:\users\common\pictures\2008";
string[] subs = path.Split('\\');
int count = 0;
while (subs[count] != "pictures")
{
count++;
}
string newPath = "";
for (int i = count; i < subs.Length; i++)
{
newPath = Path.Combine(newPath ,subs[i]);
}
Console.WriteLine(newPath);
Also prefer the use, if possible, of Path.Combine since it take care of the escape char for you.
Firstly, C# treats the '\' character as an escape character in a string, so you need to double it up to work.
string path = "#c:\\users\\common\\pictures\\2008";
string newPath = path.Substring(path.IndexOf("\\pictures\\") + 1);
What this does is take a substring of the 'path' starting at point after where "\pictures\" starts (because you don't want the initial '\').
Or this:
string path = "#c:\\users\\common\\pictures\\2008";
string[] subs = path.Split('\\');
int count = Array.IndexOf(subs, "pictures");
string newPath = String.Join("\\", subs, subs.Length - count);
Takes the path, splits into an array of the folders, finds the index of the element in the array that is 'pictures' and then joins the array starting at that point.
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;
My intention is using File.ReadAllText to read a text file line by line. After that, I will check each string array if it contains the keyword that I expected, I will take the whole string out and display it into a textbox. So here is my code :
OpenFileDialog fopen = new OpenFileDialog();
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if(fopen.FileName != "")
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
//string readtext = File.ReadAllText(save);
//string[] readtext1 = readtext.Split('\n');
string[] readline = File.ReadAllLines(save);
int lines = readline.Count();
textBox2.Text = readtext;
for (int i = 0; i < lines; i++ )
{
if (readline[i].Contains("CPL"))
{
int len = readline[i].Length;
textBox3.Text = readline[i].Substring(2, len - 4);
textBox3.AppendText(Environment.NewLine);
}
}
The problem is : if the input file look like
<>something<>
<>something1<>
<>something2<>
<>something3CPL<>
<>something4CPL<>
<>something5CPL<>
The output is always just the last string array. (here is something5CPL).
What I expected is
something3CPL
something4CPL
something5CPL
Can anybody tell me what is wrong with my code?
Thank you.
You're assigning (overwriting) the text in the textbox each iteration, so it'll only hold the last value you get from the file:
textBox3.Text = readline[i].Substring(2, len - 4);
Instead, use the same technique (appending) as you did with the Environment.Newline:
textBox3.AppendText(readline[i].Substring(2, len - 4));
This will keep adding the new values onto the end of the textbox's existing text, as you want.
You need to append the text each instead of setting the text in each iteration:
textBox3.AppendText(readline[i].Substring(2, len - 4));
May be in place of
textBox3.Text = readline[i].Substring(2, len - 4);
use
textBox3.Text += readline[i].Substring(2, len - 4);
As a textbox you can't see the results vertically.
Anyway this is the solution:
OpenFileDialog fopen = new OpenFileDialog();
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if(fopen.FileName != "")
{
textBox1.Text = fopen.FileName;
string save = fopen.FileName;
string save1 = save.Split('.')[0];
//string readtext = File.ReadAllText(save);
//string[] readtext1 = readtext.Split('\n');
string[] readline = File.ReadAllLines(save);
int lines = readline.Count();
textBox2.Text = readtext;
for (int i = 0; i < lines; i++ )
{
if (readline[i].Contains("CPL"))
{
int len = readline[i].Length;
textBox3.Text += (readline[i].Substring(2, len - 4) + " ");
}
}
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.