I have a string coming in the format:
div, v6571, 0, div, v8173, 300, p, v1832, 400
I want to split this string into multiple arrays, for the example above I would need 3 arrays, such that the format would be like this:
item[0] -> div
item[1] -> v6571
item[2] -> 0
I know that I can just do a .Split(',') on the string and put it into an array, but that's one big array. For the string example above I would need 3 arrays with the structure provided above. Just getting a bit confused on the iteration over the string!
Thanks!
I'm not sure exactly what you're looking for, but to turn the above into three separate arrays, I'd do something like:
var primeArray = yourString.Split(,);
List<string[]> arrays = new List<string[]>();
for(int i = 0; i < primeArray.Length; i += 3)
{
var first = primeArray[i];
var second = primeArray[i+1];
var third = primeArray[i+2];
arrays.Add(new string[] {first, second, third});
}
Then you can iterate through your list of string arrays and do whatever.
This does assume that all of your string arrays will always be three strings long- if not, you'll need to do a foreach on that primeArray and marshal your arrays more manually.
Here's the exact code I used. Note that it doesn't really change anything from my original non-compiled version:
var stringToSplit = "div, v6571, 0, div, v8173, 300, p, v1832, 400";
List<string[]> arrays = new List<string[]>();
var primeArray = stringToSplit.Split(',');
for (int i = 0; i < primeArray.Length; i += 3)
{
var first = primeArray[i];
var second = primeArray[i + 1];
var third = primeArray[i + 2];
arrays.Add(new string[] { first, second, third });
}
When I check this in debug, it does have all three expected arrays.
.Split(",") is your best bet. You can then modify that string array to reflect whatever structure you need.
You could use Regular Expressions or other methods, but nothing will have the performance of String.Split for this usage case.
The following assumes that your array's length is a multiple of three:
var values = str.Split(',')
string[,] result = new string[values .Length / 3, 3];
for(int i = 0; i < params.Length; i += 3)
{
int rowIndex = i / 3;
result[rowIndex, 0] = values [i];
result[rowIndex, 1] = values [i + 1];
result[rowIndex, 2] = values [i + 2];
}
Compiled in my head, but it should work.
Just so that I'm understanding you right, you need to sort them into:
1) character only array
2) character and number
3) numbers only
If so, you can do the following:
1) First try to parse the string with Int32.Parse
if successful store in the numbers array
2) Catch the exception and do a regex for the numbers
to sort into the remainder 2 arrays
Hope it helps (: Cheers!
Related
So, i have this array which contains a bunch of numbers. I want to always take 3 of those chars and make one integer out of them. I haven't found anything on this yet.
here is an example:
string number = "123456xyz";
The string is what I have, these integers are what I want
int goal1 = 123;
int goal2 = 456;
int goaln = xyz;
It should go through all the chars and always split them into groups of three. I think foreach() is going to help me, but im not quite sure how to do it.
Something like this:
var goals = new List<int>();
for (int i = 0; i + 2 < number.Length; i += 3)
{
goals.Add(int.Parse(number.Substring(i,3)));
}
This has no error checking but it shows the general outline. Foreach isn't a great option because it would go through the characters one at a time when you want to look at them three at a time.
var numbers = (from Match m in Regex.Matches(number, #"\d{3}")
select m.Value).ToList();
var goal1 = Convert.ToInt32(numbers[0]);
var goal2 = Convert.ToInt32(numbers[1]);
...
I would like to add a column of zeros to all of my double[] in my List<List<double[]>>().
The length of the double[] is currently 2 and I would like to have doubles[] of length 3. The zero should always be in the third position, for example:
double[50, 75] // double [50,75,0]
This has to be done in all of the List<double[]> within List<List<double[]>>.
Is there a short way to do this?
There is a short way of doing this in terms of lines of code, but the number of allocations and copying is equal to the number of arrays in the original list:
var res = orig.
Select(list => list
.Select(array => array.Concat(new[] {0.0}).ToArray())
.ToList()
).ToList();
Demo.
because you want to extend the array in the source list you need to manipulate them in the internal list:
foreach (var list in rootList)
{
for (var i = 0; i < list.Count; i++)
{
var actor = list[i];
list[i] = new double[actor.Length + 1]; // all elements will be 0....
Array.Copy(list[i], actor, actor.Length); //just add the prev elements
}
}
the above operation will apply the change on all pointers to List<List<double[]>>.
if you don't want to make the change on all pointer to rootList, #dasblinkenlight answer is good enough.
I have a Array in c#.
public string[] alphabet = new string[] { "A","B","C",.......}
I want to return each and every elements which between two mentioned element.
Ex:
I want to return all elements in between "A" and "D". It should return {A,B,C,D} as result.
How can I do this? Is there any build in support or Are we suppose to write our own? Please help me.
Try GetRange():
alphabetList = alphabet.ToList();
string[] range = (alphabetList.GetRange(alphabetList.IndexOf("A"), alphabetList.IndexOf("D") + 1)).ToArray();
If its only about Alphabet array then we can call a loop and then cast its variable to char.
var fist = Array.IndexOf(alphabet, "A");
var second = Array.IndexOf(alphabet, "D");
var newArray = alphabet.Skip(fist).Take(second - fist + 1).ToArray();
OR
var newArray2 = alphabet.ToList().GetRange(fist, second - fist + 1).ToArray();
I do have a string like the following
"1 1/2 + 2 2/3"
Now i want the "1 1/2" as a variable, and the "2 2/3" as a different variable.
How do i fix this?
Thanks.
If you are always going to have a '+' inbetween, you could simply do:
var splitStrings = stringWithPlus.Split('+');
for (int i = 0; i < splitStrings.Length; i++) {
splitStrings[i] = splitStrings[i].Trim();
}
edit: If you really wanted to put these two parts into two separate variables, you could do so. But it's quite unnecessary. The type of the var is going to be string[] but to get them into two variables:
var splitStrings = stringWithPlus.Split('+');
for (int i = 0; i < splitStrings.Length; i++) {
splitStrings[i] = splitStrings[i].Trim();
}
string firstHalf = splitStrings[0];
string secondHalf = splitStrings[1];
It would be better though, to just access these strings via the array, as then you're not allocating any more memory for the same data.
If you are comfortable with Linq and want to shorten this (the above example illustrates exactly what happens) you can do the split & foreach in one line:
var splitStrings = stringWithPlus.Split('+').Select(aString => aString.Trim()).ToArray();
string firstHalf=splitStrings[0];
string secondHalf=splitStrings[1];
If this syntax is confusing, you should do some searches on Linq, and more specifically Linq to Objects.
To make it shorter I used Linq to Trim the strings. Then I converted it back to an array.
string[] parts = stringWithPlus.Split('+').Select(p => p.Trim()).ToArray();
Use them as:
parts[0], parts[1]... parts[n - 1]
where n = parts.Length.
Thanks for the help with my question about making an array of booleans into a string. The code is now working good. Now I have another problem. Maybe somebody would like to try. I think I could come up with a solution but if so I'm 99 percent sure that it would be not so simple as the answers I have seen from people here.
What I have is the string "ABD" from my question here. I also have an array of integers. For example [0] = 2, [1] = 3 and [2] = 1. I would like to find a way to apply this to my string to reorder the string so that the string changes to BDA.
Can anyone think of a simple way to do this?
If those integers are 1-based indices within the string (i.e. 2 = 2nd character), then you could do this:
string s = "ABD";
int[] oneBasedIndices = new [] { 2, 3, 1 };
string result = String.Join(String.Empty, oneBasedIndices.Select(i => s[i-1]));
NB: If you are using a version less than C# 4.0, you need to put a .ToArray() on the end of the select.
What this is doing is going through your int[] and with each int element picking the character in the string at that position (well -1, as the first index in an array is 0, but your example starts at 1).
Then, it has to do a String.Join() to turn that collection of characters back into a String.
As an aside, I'd recommend downloading LINQPad (no connection) - then you can just paste that code in there as a C# Program, and at any point type variable.Dump(); (e.g. result.Dump(); at the end) and see what the value is at that point.
First make a copy of the string. The copy will never change; it serves as your reference to what the values used to be.
Then loop through the original string one character at a time using a for loop. The counter in the for loop is the position of which character in the original string we are replacing next. The counter is also the index into the array to look up the position in the original string. Then replace the character at that position in the original string with the character from the copied string.
string orig = "ABD";
int[] oneBasedIndices = new [] { 2, 3, 1 };
string copy = orig;
for ( int i = 0; i < orig.Length; i++ )
{
orig[i] = copy[ oneBasedIndices[i] - 1 ];
}
There you have it. If the indices are zero based, remove the - 1.
Napkin code again...
string result = "ABD"; // from last question
var indecies = new []{ 1,2,0 };
string result2 = indecies.Aggregate(new StringBuilder(),
(sb, i)=>sb.Append(result[i]))
.ToString();
or a different version (in hopes of redeeming myself for -1)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < indecies.Length; i++)
{
sb.Append(result[i]); // make [i-1] if indecies are 1 based.
}
string result3 = sb.ToString();