Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
How should i handle this error in my code? I tried changing List to List but there will be error at this statement :
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff);
Shown below is part of the code that I'm doing..
List<string[]> dataCollection = new List<string[]>();
List<string> timeCollection = new List<string>();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff");
if (x == unit && count == 3)
{
dataCollection.Add(ReceivedData);
timeCollection.Add(time);
for (int i = 0; i < dataCollection.Count(); i++) //write out all the data lines
{
string[] dataArray = dataCollection[i];
string dataOutput = "";
for (int j = 0; j < dataArray.Length; j++)
{
dataOutput += dataArray[j] +" "; //Link all data to write out
}
for (int k = 4; k > timeCollection.Count(); k--)
{
string[] timeArray = timeCollection[k]; //error for timeCollection[k]
string timeOutput = "";
for (int t = 0; t < timeArray.Length; t++)
{
timeOutput += timeArray[t];
}
}
The object timeCollection is a list of strings, so when you access an element of the list (timeCollection[k]) you are returning a string, yet you are trying to assign it to an array.
string[] timeArray = timeCollection[k];
Try this instead:
string timeValue = timeCollection[k]
Or you might need to modify timeCollection so that it is a list of string arrays, but that doesn't seem to be the case because the variable time is just a string and not an array.
It also seems to me that your two for loops could be replaced by these lines:
string dataOutput = String.Join(" ", dataCollection.SelectMany(x => x));
string timeOutput = String.Join("", timeCollection.Take(4).Reverse());
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I need to return every substring within a string array that is contained by the its integer index using for loops and if statements.
I managed to split the array and create a for loop but I am stuck when trying to compare the locations of the values using the variables.
string[] text = "The brown fox jumps";
char split = " ";
int cutFrom = '2';
int cutTo = '4';
string[] splitText = text.Split(split);
for (int i = 0; i < splitText.Length; i++)
{
if (parts[i] == parts[cutFrom])
{
return parts[i];
}
}
But this code only returns the "brown" (the 2nd array subtext), and I want to return every word from the second value until the 4th value in the array ("jumps").
Your question was a bit weirdly asked but I've tried to interpret it as best as I can.
Here is the solution for what you said:
private string[] getSubstrings(string text, char split, int cutFrom, int cutTo)
{
string[] splitText = text.Split(split);
string[] output = new string[cutTo - cutFrom];
for (int i = cutFrom; i < cutTo; i++)
{
output[i - cutFrom] = (splitText[i]);
}
return output;
}
Here is the solution with 1 based indexing which is what I think you wanted (getting the first word only is cutFrom = 1; and cutTo = 2)
private string[] getSubstrings(string text, char split, int cutFrom, int cutTo)
{
cutFrom--;
cutTo--;
string[] splitText = text.Split(split);
string[] output = new string[cutTo - cutFrom];
for (int i = cutFrom; i < cutTo; i++)
{
output[i - cutFrom] = (splitText[i]);
}
return output;
}
It is not entirely clear what your approach is here. If you want to return a list of substrings from index cutFrom to index cutTo from a larger string, then you could approach it like this:
string text = "The brown fox jumps";
string split = " ";
int cutFrom = 2;
int cutTo = 4;
string[] splitText = text.Split(split);
List<string> finalStrings = new List<string>();
for (int i = 0; i < splitText.Length; i++)
{
if (i >= cutFrom && i < cutTo)
{
finalStrings.Add(splitText[i]);
}
}
return finalStrings;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
I have a list of string with comma separated in each of them.
For eg:
abc,1,2,0,0,0,3,1,0
def,2,0,1,0,0,1,0,0
I would like to generate a summation of that two strings starting from index 1 of each string.
Output eg:
Output,3,2,1,0,0,4,1,
Below is my current code. But I am looking for shorter version of it.
List<string> panelBinCodeStringList = new List<string>;
//panelBinCodeStringList has more than 2 strings.
List<int> totalTmpString = new List<int>();
foreach (var binCodeString in panelBinCodeStringList)
{
var tmp = binCodeString.Substring(binCodeString.IndexOf(',') + 1).Split(',').ToList();
for (int i =0; i < tmp.Count; i++)
{
if (totalTmpString.Count() <= i)
{
totalTmpString.Add(Convert.ToInt16(tmp[i]));
}
else
{
totalTmpString[i] += Convert.ToInt16(tmp[i]);
}
}
}
totalFailedBinCodes = "Output," + string.Join(",", totalTmpString);
Not very efficient, but working.
var abcTxt = "abc,1,2,0,0,0,3,1,0";
var defTxt = "def,2,0,1,0,0,1,0,0";
var abcList = abcTxt.Split(",").Skip(1).Select(int.Parse).ToList();
var defList = defTxt.Split(",").Skip(1).Select(int.Parse).ToList();
if (abcList.Count != defList.Count)
throw new Exception("Collections do not have the same size");
var output = "Output";
for (var i = 0; i < abcList.Count; i++) output += "," + (abcList[i] + defList[i]);
Result:
string[] a = abc.Split(",");
string[] d = def.Split(",");
String output = "Output";
for(int i= 1; i < a.Length; i++)
{
output+= "," + (int.Parse(a[i]) + int.Parse(d[i]));
}
Approach with Linq.Zip()
string s1 = "abc,1,2,0,0,0,3,1,0";
string s2 = "def,2,0,1,0,0,1,0,0";
Func<string, IEnumerable<int>> ToInt = x => x.Split(',').Skip(1).Select(int.Parse);
string res = "output," + string.Join(",", ToInt(s1).Zip(ToInt(s2),(x, y) => x+y));
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
private void Button4_Click(object sender, EventArgs e) {
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using(var streamReader = new StreamReader(start)) {
string line = streamReader.ReadLine();
int[] values = line.Split(' ').Select(int.Parse).ToArray();
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
Hey guys I need more information about this code. Could anyone explain me how it works. I mostly googled it so dont know how it works. Also I have added .txt file and got access to first row, but i need to get into 7 and 8 row. There's just random numbers in that .txt file.
Ok so there's a better way to do this. StreamReader has a .Peek() method that is extremely useful for reading to the end of a file. Basically the only thing you're missing is a way to loop through each line in your file.
Start with your using statement.
using(var streamReader = new StreamReader(start)) {...
//Using statement is a way for you to close your stream after the work
//is completed. This is why you need to get a loop inside of here.
Use a loop to read to the end of a file.
This part is what I'd change in your code. Your Using statement will not loop. You have to tell it to loop. Peek() returns -1 or the next character to be read. So you can use this to your advantage to check if you want to read to the end of file. Review the documentation here. https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader.peek?view=netframework-4.8
while(streamReader.Peek() > -1)
{...
Then you can split to your array per line by simply reading in each or splitting to a character.
int[] values = streamReader.Readline().Split(' ');
Finally you can do the remainder of your code.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
To break down exactly what is going on in your code. Read each comment line by line to get a basic understanding.
//Button Click Event
private void Button4_Click(object sender, EventArgs e) {
//Finding your file and assigning it as a string.
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
//Using a `using` statement and creating a new streamReader that will look
//for the string that you created above to find the file. The using block
//will properly close the streamreader when the work is done.
using(var streamReader = new StreamReader(start)) {
//StreamReader.ReadLine() will read the FIRST line, no loop here.
//This is why your code only reads one.
string line = streamReader.ReadLine();
//Splitting to an array.
int[] values = line.Split(' ').Select(int.Parse).ToArray();
//Sorting array.
Array.Sort(values);
//Reversing the array.
Array.Reverse(values);
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
richTextBox4.AppendText(values[i] + " ");
}
}
}
If you're attempting to only get rows 7, 8, 9, etc.. within your for loop at the very end of your code do the following.
//Looping through the array based on count.
for (int i = 0; i < values.Length; i++) {
//This will only append rows 7-9. Keep in mind an array is a 0 based
//index. Meaning row 7 is actually array element 6. Row 9 is actually
//array element 8.
if(i > 5 && i < 9){
richTextBox4.AppendText(values[i] + " ");
}
}
}
}
So my current code looks like this:
private void Button4_Click(object sender, EventArgs e)
{
string start = Directory.GetCurrentDirectory() + #"\Sav1.txt";
using (var streamReader = new StreamReader(start))
{
while (streamReader.Peek() > -1)
{
string[] values = streamReader.ReadLine().Split(' ');
Array.Sort(values);
Array.Reverse(values);
for (int i = 0; i < values.Length; i++)
{
richTextBox4.AppendText(values[i] + " ");
}
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
C# I want to know How to place a comma after every digit of a long type number (input parameter) separating even and odds?
Example: InsertComma(12272358) should return "1,22,7,2,35,8"
Using LINQ:
private static string InsertComma(long v)
{
var strArray = v.ToString().ToArray();
//compares current element to next one and insert separator if is needed
//last element is ignored due to preventing index exeption
var result = strArray.Take(strArray.Length-1)
.Select((x, index) => ((x % 2) == (strArray[index+1]%2)) ? x.ToString() :x+ ",");
return string.Join("", result)+strArray.Last() ;
}
Using For loop:
private static string InsertComma(long v)
{
var result = "";
var strArray = v.ToString().ToArray();
int i = 0;
for ( i = 0; i < strArray.Length-1; i++)
{
result += strArray[i];
//compares current element to next one and insert separator if is needed
if ((strArray[i]%2) != (strArray[i + 1] % 2))
result += ",";
}
return result + strArray[i];
}
Use:
Console.WriteLine(InsertComma(12272358));
Output:
1,22,7,2,35,8
The simpliest way to enumerate thought a Int's digits is to make it a string.
Then for each element of this string we will lock it it's has the same reminder than the previous element in this case we need to concatenate them. Except for the first element as there is no previous.
var input = 54721704;
var str = input.ToString();
var result = new List<string>();
for (int i = 0; i < str.Length; i++)
{
if (i == 0)
{
result.Add(str[i].ToString());
continue;
}
if (Char.GetNumericValue(str[i]) % 2 == Char.GetNumericValue(str[i - 1]) % 2)
{
result[result.Count() - 1] += str[i].ToString();
}
else
{
result.Add(str[i].ToString());
}
}
Console.WriteLine(string.Join(", ", result));
https://rextester.com/UML19116
You can improve this by avoiding unnecesseray access to the previous element casting and modulo computation by storing the result in a variable.
Covert to string and then loop.
string CovertNumber(int source) {
var result = new StringBuilder();
var src = source.ToString();
var wasEven = false;
for (var i =0; i < src.Length; i++) {
var digit = int.Parse(src[i].ToString());
var isEven = (digit % 2) == 0;
if (i > 0 && isEven != wasEven) {
result.Append(",");
}
result.Append(digit.ToString());
wasEven = isEven;
}
return result.ToString();
}
This code will bomb on a negative number so you will need to validate input or use Math.Abs to ignore the sign.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following C# method to split a path string.
Only thing I know is a fixed string in the path and I have to split the full path into two parts, first part should be one level below the fixed string and the rest should be the second part.
For example, if I have the following path,
string mainText = #"C:\Abc\Fixed\MyTemp\Japan\Tokyo";
then my firstPart would be "C:\Abc\Fixed\MyTemp" and second part "Japan\Tokyo"
I want to improve this method in terms of memory and speed.
private static void SplitPath(string mainText, out string firstPart, out string secondPart)
{
firstPart = string.Empty;
secondPart = string.Empty;
if (!string.IsNullOrEmpty(mainText))
{
string strConstatnt = "Fixed";
List<string> splitted = mainText.Split(new char[] { '\\' }).ToList();
int indexToFixed = splitted.IndexOf(strConstatnt);
StringBuilder sbFirst = new StringBuilder();
StringBuilder sbSecond = new StringBuilder();
if (indexToFixed >= 0)
{
for (int i = 0; i < splitted.Count; i++)
{
if (i < (indexToFixed + 2))
{
sbFirst.Append(splitted[i] + "\\");
}
else
{
break;
}
}
for (int i = (indexToFixed + 2); i < splitted.Count; i++)
{
sbSecond.Append(splitted[i] + "\\");
}
}
if (sbFirst.Length > 0)
{
firstPart = sbFirst.Remove(sbFirst.Length - 1, 1).ToString();
}
if (sbSecond.Length > 0)
{
secondPart = sbSecond.Remove(sbSecond.Length - 1, 1).ToString();
}
}
}
Here's a little sample (assuming you want to split after Fixed):
static void Main(string[] args)
{
var input = #"C:\Abc\Fixed\MyTemp\Japan\Tokyo";
foreach (var item in Regex.Split(input, #"(?<=Fixed\\(?=[^\\]+))"))
Console.WriteLine(item);
}
Instead of building the result using for loops and StringBuilder you can use String.Join to combine the parts in splitted:
firstPart = String.Join(#"\", splitted.Take(indexToFixed + 2);
secondPart = String.Join(#"\", splitted.Skip(indexToFixed + 2);