C# replace strings in array with LINQ - c#

I have an string array of size 10:
[0] = "1,0000000"
[1] = "479,00000"
....
[9] = "145,0".
I want to remove the trailing ",00000" of the first 9 elements with regex and linq. Please help.

Basically I would do this like that :
var yourArray = new string[10];
var yourResult = yourArray.Take(9).Select(s => s.Split(',')[0]).ToArray();
But you can replace the Select method content with a Regex call if you wish.

Use a for-loop and string methods like IndexOf and Substring:
for(int i = 0; i < Math.Min(array.Length, 9); i++)
{
int commaIndex = array[i].IndexOf(",");
if(commaIndex >= 0) array[i] = array[i].Substring(0, commaIndex);
}

You can simply try
data.forEach(x => x.replace("ABC", "'"));

Related

Copy String byte Array contents to another array and Prefix 0 to single digits in C#

I have String array named "string_array_packet" which contains
FA,11,1,4,90,6C,E7,72,0,0,0,8,80,0,8,80,7B,
Now i need to copy the contents between first and last index of array and store it in another array and then need to prefix 0 to single digits
11,1,4,90,6C,E7,72,0,0,0,8,80,0,8,80,
What I have done so far is
var sourceStartIndex = 1;
var destinationLength = string_array_packet.Length - 2;
Console.WriteLine(string_array_packet.Length);
Console.WriteLine(destinationLength);
var destinationStartIndex = 0;
var destination = new string[destinationLength];
Array.Copy(string_array_packet, sourceStartIndex,
destination, destinationStartIndex, destinationLength);
Not sure how to proceed after this.
This can be done much easier with Linq (using System.Linq required):
var sourceStartIndex = 1;
var destinationLength = string_array_packet.Length - 2;
var strings = string_array_packet.Skip(sourceStartIndex)
.Select(x => x.Length == 1 ? "0" + x :x)
.Take(destinationLength)
.ToArray();
Alternatively, if you're not familiar with the Enumerable methods then add the following imperative approach to complete your code:
for (int i = 0; i < destination.Length; i++)
if (destination[i].Length == 1)
destination[i] = "0" + destination[i];

Convert a string into a byte array in c#

I have a string,
string Var="11001100"
I want to convert it into a byte array.
bArray[0]=0x00;
bArray[1]=0x00;
bArray[2]=0x01;
bArray[3]=0x01;
bArray[4]=0x00;
bArray[5]=0x00;
bArray[6]=0x01;
bArray[7]=0x01;
Can anybody guide me in this? I tried the following code, but I get the data in ASCII. I do not want that.
bArray = Encoding.Default.GetBytes(var);
I suggest using Linq:
using System.Linq;
...
string Var = "11001100";
byte[] bArray = Var
.Select(item => (byte) (item == '0' ? 1 : 0))
.ToArray();
Test:
Console.WriteLine(string.Join(Environment.NewLine, bArray
.Select((value, index) => $"bArray[{index}]=0x{value:X2};")));
Outcome:
bArray[0]=0x00;
bArray[1]=0x00;
bArray[2]=0x01;
bArray[3]=0x01;
bArray[4]=0x00;
bArray[5]=0x00;
bArray[6]=0x01;
bArray[7]=0x01;
but I get the data in ASCII. I do not want that.
Then you need the string representation of the chars. You get it using the ToString method. This would be the old scool way simply using a reversed for-loop:
string Var="11001100";
byte [] bArray = new byte[Var.Length];
int countForward = 0;
for (int i = Var.Length-1; i >= 0 ; i--)
{
bArray[countForward] = Convert.ToByte(Var[i].ToString());
countForward++;
}
This is my solution for your question:
string value = "11001100";
int numberOfBits = value.Length;
var valueAsByteArray = new byte[numberOfBits];
for (int i = 0; i < numberOfBits; i++)
{
bytes[i] = ((byte)(value[i] - 0x30)) == 0 ? (byte)1 : (byte)0;
}
Edit: Forgot the inversion.

Write list to csv file c#

Imagine i have 2 lists filled with values. I want all the elements from the first list, written into the first column, all the elements from the second list written into the second column and so on.
If both list have the same size, this works fine:
for (int i = 0; i < valueArray.Count(); i++)
{
var newLine = string.Format("{0},{1}", valueArray.ElementAt(i), secondValueArray.ElementAt(i));
sw.Write(newLine);
}
My problem is that if the lists have different sizes, code fails with out of range exception obviously. I tried adding ',' between columns but it's not working.
Instead of ElementAt you should use ElementAtOrDefault :
According to msdn it
Returns the element at a specified index in a sequence or a default
value if the index is out of range.
try this :
List<int?> valueArray = new List<int?>();
List<int?> secondValueArray = new List<int?>();
//... fill lists
valueArray.Add( 1 );
valueArray.Add(2);
valueArray.Add(3);
secondValueArray.Add( 4 );
while (valueArray.Count > secondValueArray.Count)
secondValueArray.Add(null);
while (secondValueArray.Count > valueArray.Count)
valueArray.Add(null);
for (int i = 0; i < valueArray.Count(); i++)
{
var newLine = string.Format("{0},{1}", valueArray.ElementAt(i), secondValueArray.ElementAt(i));
Console.WriteLine(newLine);
}
;
Result :
1,4
2,
3,
As mentioned before, use ElementAtOrDefault(). And check which array is the longest one. Furthermore, you might want to write an empty string instead of NULL if there's no value.
int count = Math.Max(firstArray.Count(), secondArray.Count());
for (int i = 0; i < count; i++)
{
var value1 = firstArray.ElementAtOrDefault(i) ?? String.Empty;
var value2 = secondArray.ElementAtOrDefault(i) ?? String.Empty;
var newLine = string.Format("{0},{1}", value1, value2);
sw.Write(newLine);
}

c# For every 7 letters in the string add item string to Listbox

ListBox box = GetListBox(); //placeholder for the sample
string s = "123456776543219898989";
char[] c = s.ToCharArray();
for(int i=0;i<c.Length;i+=7)
{
box.Items.Add(new string(c, i, 7));
}
This is fast way to separate text.
you can do an easy for loop
ListBox box = null;//set it yourself
for(int i = 0; i < s.Length; i+= 7)
{
box.Items.Add(s.SubString(i, Math.Min(s.Length - i, 7));
}
Break the string into a character array, and use that to create your items. This string constructor overload will help:
http://msdn.microsoft.com/en-us/library/ms131424.aspx
This code is just a sample. What you actually need will depend on how you want to handle the situation where the number of characters in the original string is not evenly divisible by 7.
ListBox box = GetListBox(); //placeholder for the sample
string s = "123456776543219898989";
char[] c = s.ToCharArray();
for(int i=0;i<c.Length;i+=7)
{
box.Items.Add(new string(c, i, 7));
}
I could also do this directly on the string, instead of creating the array, but this should be much faster than calling .SubString() repeatedly.
var str = "123456776543219898989";
int count = 0;
var parts = str.GroupBy(_ => count++ / 7)
.Select(x => string.Concat(x))
.ToArray();
listBox1.Items.AddRange(parts);

Why im getting 0 all the time when using indexOf?

for (int i = 0; i < links.Count; i++)
{
int f = links[i].IndexOf("http");
}
links is List<string>
For example in index 0 I have: http://test/107281.shtml#34
I want to extract from this link only this:
http://test/107281.shtml without the #34 in the end.
But for the start why f return 0 all the time ?
It's right...., cause this string "http" start index is 0, if couldn't found string, IndexOf will return -1...
The first char in a string is located at index 0, so in the string http://test/107281.shtml#34 as http is the first thing in the string its located at index 0...
To extract you can use either regex or indexOf("#") in combination with substring.
The indexOf() method returns the position of the first occurrence of a specified value in a string.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
Output wil be : 13
which is the position number.
Next you remove from which position you want to delete.
I guess you are looking for something like:
for (int i = 0; i < links.Count; i++)
{
int f = links[i].IndexOf("#");
}
This should give you the index of the first #.
IndexOf("http") should give you 0 as http is at index 0.
To get the string you are seeking:
for (int i = 0; i < links.Count; i++)
{
var url = links[i].Substring(0, links[i].IndexOf("#"));
}
Example using your demo string HERE.
List<string> link_list = new List<string> { "http://test/107281.shtml#34", "http://test/107281.shtml#35" };
List<string> new_list = new List<string>();
foreach (var item in link_list)
{
string bb = item.Substring(0, item.ToString().IndexOf("#"));
new_list.Add(bb);
}

Categories