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));
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 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 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 5 years ago.
Improve this question
I have text file (words.text) includes lines each line have characters and equivalent words like this:
A = 1
B = 2
C = 3
D = 4
I used following code to read text file
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\words.txt");
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
counter++;
}
I need to change the value of each character (number) by counter and saved it again in way to be like this
A = 3
B = 4
C = 1
D = 2
I thought about makes each word and = to be "first" and number is "second", and loop the second one
First = "A = ", Second = "1"
I have no idea how to make program to read each line and identified first and second one
You can simply split each line value by = character to get first and second value:
System.IO.StreamReader file =
new System.IO.StreamReader(#"c:\words.txt");
while((line = file.ReadLine()) != null)
{
string[] split = line.Split('=');
string First = split[0] + " = ";
string Second = split[1];
//actually you can use split[0] and split[1], the two above llines are for demo
counter++;
}
How about this...
// Getting content of the file.
string contents = File.ReadAllText(#"C:\test.txt");
// Separating content
string[] contentArr = contents.Split('\n');
List<string> characterList = new List<string>();
List<int> valueList = new List<int>();
foreach (string value in contentArr)
{
characterList.Add(string.Join("", value.ToCharArray().Where(Char.IsLetter)).Trim());
valueList.Add(Int32.Parse(string.Join("", value.ToCharArray().Where(Char.IsDigit))));
}
All the characters will be stored in the characterList as a string and all the value will be stored in the valueList as integers (int).
If you need to read or change values, you can do it like this using a forloop (or a foreach).
for (int i = 0; i < contentArr.Length; i++)
{
//valueList[i] = 5
Console.WriteLine(characterList[i] + " = " + valueList[i]);
}
//// characters
//foreach(string value in characterList)
//{
// Console.WriteLine(value);
//}
//// Values
//foreach(int value in valueList)
//{
// Console.WriteLine(value);
//}
Or, you can change value individually...
valueList[0] = 3;
valueList[1] = 4;
valueList[2] = 1;
valueList[3] = 2;
After making changes, you can write back to the file.
string output = "";
for (int i = 0; i < contentArr.Length; i++)
{
output += characterList[i] + " = " + valueList[i] + Environment.NewLine;
}
File.WriteAllText(#"C:\test.txt", output);
Online Sample 01: http://rextester.com/TIVM24779
Online Sample 02: http://rextester.com/KAUG79928
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());
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);