Replace substring from the listbox (WindowsForms) - c#

I have attached in my listbox ( lb1 ) a character to the previous item. The letter A is seperated by a comma. Is it even possible to replace the letter in this line
(A --> B)? How can this be solved? The result in the listbox( lb2 ) should look as shown below.
if (listBox1.Items.Cast<string>().Contains("someText"))
{
int a = listBox1.Items.IndexOf("someText");
listBox1.Items.RemoveAt(a);
listBox1.Items.Insert(a, "newText");
}

Here is a code snippet for your new problem mikee:
You need to iterate through the items of the list box, search for a match, and replace the detected matches:
string search = "A";
string replace = "B";
for(int i = 0; i < lb1.Items.Count; i++)
{
if(lb1.Items[i].ToString().EndsWith(search))
{
string item = lb1.Items[i].ToString().Replace(search, replace);
lb1.Items[i] = item;
}
}
Edit
Please note that, the preceding snippet will change all the A characters in the string with B not only the last one. So if you have a list item say JONATHAN, A, the preceding code will change it to JONBTHBN, B. To avoid that you could do:
Solution 1:
for (int i = 0; i < lb1.Items.Count; i++)
{
if (lb1.Items[i].ToString().EndsWith(search))
{
int indx = lb1.Items[i].ToString().LastIndexOf(search);
string item = lb1.Items[i].ToString().Substring(0, indx) + replace;
lb1.Items[i] = item;
}
}
Solution 2:
If all of your list items are comma separated strings like the image above, then you could do:
for (int i = 0; i < lb1.Items.Count; i++)
{
if (lb1.Items[i].ToString().EndsWith(search))
{
var arr = lb1.Items[i].ToString().Split(',');
arr[arr.Length - 1] = replace;
lb1.Items[i] = string.Join(", ", arr);
}
}
Sorry for any inconvenience mikee.
Good luck.

Related

C# - Foreach two line in Text File

I am developing in C#.
I have a text file containing the following:
Sam
NYC
Mii
Peru
LEO
Argentina
I want to iterate through this file two line by two line, then print to the console the first line, second line (the Name and the Country) of each couple, so the output would be:
Sam, NYC
Mii, Peru
Here is what I have tried:
int linenum = 0;
foreach (string line in File.ReadLines("c:\\file.txt"))
{
string word = line;
string s = "";
string j = "";
linenum = linenum + 1;
if(linenum % 2 != 0) //impaire
{
s = line;
}
else
{
j = line;
}
Console.WriteLine((string.Concat(s, j));
}
But that's not working, I want to do:
int linenum = 0;
foreach( two lines in File.ReadLines("c:\\file.txt"))
{
linenum = linenum + 1;
//get the first line (linenum = 1) and store it in a string s
// then get the second line (linenum = 2) and store it in a string j
// then print the two strings together to the console like that
Console.WriteLine((string.Concat("S: " + s,"J: " j));
}
How can I do that ?
Use File.ReadAllLines to return an array of strings:
var lines = File.ReadAllLines(filePath);
for (int i = 0; i < lines.Length; i+=2)
{
var s = lines[i];
var j = lines[i+1];
Console.WriteLine($"S: {s} J: {s}");
}
You do your output with Console.WriteLine in every line, but you also should do that only for every second line. Furthermore, your variables s and j live inside the loop's scope, so they are recreated with every iteration and loose their prior value.
int i = 0; string prev = "";
foreach (string line in File.ReadLines("c:\\file.txt")) {
if (i++ % 2 == 0) prev = line;
else Console.WriteLine($"{prev}, {line}");
}
Another approach would be iterating the array you get from File.ReadAllLines with an for loop instead of foreach and increase the index by 2
var lines = File.ReadAllLines("c:\\file.txt");
//make sure, you have an even number of lines!
if (lines.Length% 2 == 0) for (int i = 0; i < lines.Length; i+=2) {
Console.WriteLine($"{lines[i]}, {lines[i+1]}");
}
You can write yourself a little helper method to return batches of lines.
This implementation handles files that are not a multiple of the batch size (2 in your case) by returning "" for the missing lines at the end of the file.
public static IEnumerable<string[]> BatchedLinesFromFile(string filename, int batchSize)
{
string[] result = Enumerable.Repeat("", batchSize).ToArray();
int count = 0;
foreach (var line in File.ReadLines(filename))
{
result[count++] = line;
if (count != batchSize)
continue;
yield return result;
count = 0;
result = Enumerable.Repeat("", batchSize).ToArray();
}
if (count > 0)
yield return result;
}
Note that this also returns a separate array for each result, in case you make a copy of it.
Given that code, you can use it like so:
foreach (var batch in BatchedLinesFromFile(filename, 2))
{
Console.WriteLine(string.Join(", ", batch));
}
Actually, you can use LINQ to get two lines in a time using Take
var twoLines = File.ReadLines(#"YourPath").Take(2));
As you can use Skip to skip the two lines you took and take the next two lines like :
var twoLines = File.ReadLines(#"YourPath").Skip(2).Take(2));
EDIT : Thanks for #derpirscher there were a performance issue so changed the code to the following :
first read the whole file and store it in a string array
then loop through it using LINQ to take two elements from the array in a time.
string[] myStringArray = File.ReadAllLines(#"YourFile.txt");
for (int i = 0; i < myStringArray.Length ; i+=2)
{
var twoLines = myStringArray.Skip(i).Take(2).ToArray();
}
Another one, using Enumerable.Repeat() and an interger selector incremented a [NumberOfLines / 2] times.
Could be interesting for the LINQ addicted (a for / foreach solution is probably better anyway).
string[] input = File.ReadAllLines([SourcePath]);
int Selector = -1;
string[] output = Enumerable.Repeat(0, input.Length / 2).Select(_ => {
Selector += 2;
return $"{input[Selector - 1]} {input[Selector]}";
}).ToArray();
The output is:
Sam NYC
Mii Peru
LEO Argentina
Use the right tool for the job. foreach() is not the right tool here.
Without giving up the memory efficiency of ReadLines() over ReadAll():
using (var lines = File.ReadLines("c:\\file.txt").GetEnumerator())
{
while (lines.MoveNext())
{
string firstLine = lines.Current;
if (!lines.MoveNext())
throw new InvalidOperationException("odd nr of lines");
string secondLine = lines.Current;
// use 2 lines
Console.WriteLine("S: " + firstLine ,"J: " + secondLine);
}
}

C# Array Different indexes

Hi i want to search for character in a string array but i need to search Between 2 indices. For example between index 2 and 10. How can I do that?
foreach (var item in currentline[2 to 10])
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
As you can see, foreach enumerates over a collection or any IEnumerable.
As the comments say, you can use a for loop instead, and pick out the elements you want.
Alternatively, since you want to search for a character in a string, you can use IndexOf, using the start index and count overload to find where a character is.
As there is no use of the c++ in your code I will assume that it's a vestige of code.
You can simply addess your issue like this:
In the currentline
Take char from index 2 to 10
Till you find a char you don't want.
concatenate the resulting char array to a string.
Resulting Code:
var data = "##";//01234567891 -- index for the string below.
var currentline= "kj[abcabc;z]Selected data will be between: '[]';";
var exceptChar = ",;";
data += new string(
input.Skip(3)
.Take(8)
.TakeWhile(x=> !exceptChar.Contains(x))
.ToArray()
);
There is a string method called string.IndexOfAny() which will allow you to pass an array of characters to search for, a start index and a count. For your example, you would use it like so:
string currentLine = ",;abcde;,abc";
int index = currentLine.IndexOfAny(new[] {',', ';'}, 2, 10-2);
Console.WriteLine(index);
Note that the last parameter is the count of characters to search starting at the specified index, so if you want to start at index 2 and finish at index 10, the count will be finish-start, i.e. 10-2.
You can search for characters in strings and get their indexes with this LINQ solution:
string str = "How; are, you; Good ,bye";
char[] charArr = { ',', ';' };
int startIndex = 2;
int endIndex = 10;
var indexes = Enumerable.Range(startIndex, endIndex - startIndex + 1)
.Where(i=>charArr.Contains(str[i]))
.ToArray();
In this case we get Enumerable.Range(2, 9) which generates a sequence between 2 and 10 and the Where clause filters the indexes of the characters in str that are matching one of the characters inside charArr.
Thanks everey one finaly i fixed it by your guid thanks all
myarr = new mytable[50];
number_of_records = 0;
number_of_records = fulllines.Length;
for (int line = 1; line < fulllines.Length; line++)
{
int c = 0;
for (int i = 0; i < record_lenth; i++)
{
string data = "";
string currentline = fulllines[line];
string value = "";
for (int x = c; x < fulllines[line].Length; x++)
{
value += currentline[x];
}
foreach (var item in value)
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
}
}

How to append every X in c# stringbuilder

I'm using unity and c# and am not sure how to use stringbuilder to append a "/" every X characters. I have code and can build a string from a array with the code below, and add a comma after each string, but i need to add the "/" after every x string
it should for example convert "122342" to "1,2,2,/,3,4,2". Currently it would convert it to "1,2,2,3,4,2"
this is the code i have already
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
Builtstring.Append(griditem).Append(",");
}
built = Builtstring.ToString();
Use a FOR loop and then check if the character is a factor of some desired nTH character. If so add an extra '/'.
int x = 2; // your x
StringBuilder builtstring = new StringBuilder();
for (int i = 0; i < tobuild.Length; i++)
{
string item = tobuild[i];
builtstring.Append(item).Append(",");
if (i%x==0) { builtstring.Append("/"); }
}
string built = builtstring.ToString();
Add an if statement to evaluate the character and then act accordingly.
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(griditem == 'x') { Builtstring.Append(griditem).Append(#"/"); }
Builtstring.Append(griditem).Append(",");
}
built = Builtstring.ToString();
Or if you actually want to count a certain number of characters before putting a slash you can do this.
int count = 10;
int position = 0;
StringBuilder Builtstring = new StringBuilder();
foreach(string griditem in tobuild){
if(position == count) { Builtstring.Append(griditem).Append(#"/"); position = 0; }
else{Builtstring.Append(griditem).Append(","); position++;}}
built = Builtstring.ToString();
You can iterate over the array of strings using a for loop, which provides an index.
For each iteration, add the current String to the StringBuilder, in addition to a ',' in case we still didn't reach the last string in the array.
Also, after x strings add a '/'. We can know that we reached x strings using the % (modulus) operator.
Notice that I start the loop from index = 1. I do that because the modulus operator for the value 0 with any positive number will yield 0, which will add the '/' char after the first word, something that we don't necessarily want.
static void Insert(StringBuilder b, int x, string[] tobuild)
{
for(var index = 1; index < tobuild.Length; ++index)
{
b.Append(tobuild[index]);
if(index != tobuild.Length -1)
{
b.Append(",");
}
if(0 == index % x)
{
b.Append("/");
}
}
}

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

Moving in text file with C#

I have a problem with C#.
I am writing code to search a text file until it finds a certain word, then the code should move three lines and read the fourth, then continue the search to find the certain word again.
Now I don't know how to navigate through the file (forward and backward) to the line I want.
Can anybody help?
You can do something like this:
var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
//Find the word the first time
if(!foundFirstTime && text[i].Contains("word"))
{
//Skip 3 lines - and continue
i = Math.Min(i+3, text.Length-1);
foundFirstTime = true;
}
if(foundFirstTime && text[i].Contains("word"))
{
//Do whatever!
}
}
// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
select lines).ToList<string>();
for (int i = 0; i < query.Count; i++)
{
if (query[i].Contains("TextYouWant"))
{
i = i + 3;
}
}
Your requirements state that you are searching for a specific word. If that is true and you are not instead looking for a specific string, then the checked answer on this is wrong. Instead you should use:
string[] lines = System.IO.File.ReadAllLines("File.txt");
int skip = 3;
string word = "foo";
string pattern = string.Format("\\b{0}\\b", word);
for (int i = 0; i < lines.Count(); i++)
{
var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);
System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));
if (match) i += skip;
}
If you use the string.contains method and the word you are searching for is "man", while your text somewhere contains "mantle" and "manual", the string.contains method will return as true.

Categories

Resources