Get All elements in between two elements in Array - c#

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

Related

Sum up numbers after splitting string and parsing to int

I am learning c# and I encounter problem when attempting to sum the numbers from console input. User inserts numbers separated with commas. Then, they get splitted and at the end they should be parsed to int's for the future calculations as sum.
Here is what I've got:
int[] convertedLine;
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success = int.TryParse(splittedLine[0], out convertedLine);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
on 4th line I get error under convertedLine, that says 'cannot convert from out int[] to out int'.
I will appreciate help that will put me on the right track with my problem.
Thank you.
P
---------- edit ------------
Ok, so I've got this code now and it works. Is there a nicer way to do this parsing for all splitted elements of a string?
int[] convertedLine=new int[3];
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success1 = int.TryParse(splittedLine[0], out convertedLine[0]);
var success2 = int.TryParse(splittedLine[1], out convertedLine[1]);
var success3 = int.TryParse(splittedLine[2], out convertedLine[2]);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
You need to initialize the elements of the convertedLine array and then specify the element you want to set to the value you pass to int.TryParse
Your .TryParse should look something like this:
var success = int.TryParse(splittedLine[0], out convertedLine[0]);
Note the [0] next to convertedLine that indicated the element in the int array you are setting
To initialize your convertedLine integer array simply do this line:
int[] convertedLine = new int[x];
Where x is the number of elements you want to have in your array. If you don't want to limit your user to a set amount of inputs you'll have to split on your split character and then initialize your integer array to however many values you found that the user input
The problem is here: int[] convertedLine; and then here: var success = int.TryParse(splittedLine[0], out convertedLine);
You are trying to parse to an array of integers a unique value of integers. Your code is assuming you have multiple integer as inputs
you are trying to convert the string to int in your case you pass an array of int and the function attempt to have an int a parameter.
try this one:
foreach(var i in splittedLine)
{
var success = int.TryParse(splittedLine[i], out convertedLine[i]);
}
The 'out' parameter from your int.TryParse is a single int. You're trying however to put that single int into an array of ints (which you've called 'convertedLine') without specifying where in the array that int should go.
One option then would be to declare your int array with a fixed size (eg)
int[5] convertedLine = new int[5];
which then allows for up to 5 integers. Then where you have
var success = int.TryParse(splittedLine[0], out convertedLine);
you should instead set a fixed value within the array, like this:
int.TryParse(splittedLine[0], out convertedLine[0]);
As an aside you also probably want to try and parse any other ints in the same way, eg:
int.TryParse(splittedLine[1], out convertedLine[1]);
int.TryParse(splittedLine[2], out convertedLine[2]);

Select certain part in string as variable c#

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.

Changing the order of a string based on an array of numbers in C#

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

Loop through comma delimited string, split into multiple arrays?

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!

Find Shortest element in Array

I have a Array
string[] names = { "Jim Rand", "Barry Williams", "Nicole Dyne", "Peter Levitt", "Jane Jones", "Cathy Hortings"};
Is there any way to find which is the shortest(Length wise) element in this array and then store rest of elements in a different array.
Thanks,
Ani
var orderedNames = names.OrderBy(name => name.Length);
string shortestName = orderedNames.First();
string[] otherNames = orderedNames.Skip(1).ToArray();
In C#, .Net 3.5:
string shortestName = names.Aggregate((n1, n2)=>n1.Length<n2.Length?n1:n2);
This is how you can store other elements in other array
var otherArrays = names.Exclude(new List<string>(){shortestName});
There is no .Exclude method (or extension method) for an Array and he didn’t say that he wanted to change the collection type for the new Array. Your use of the .Aggregate is outstanding so let’s take it one step further and use .Aggregate to do the excluding as well!
Like this:
string shortestName = names.Aggregate((n1, n2) => n1.Length < n2.Length ? n1 : n2);
string nonArrayString = names.Aggregate((n1, n2) => n2 != shortestName ? n1 + " " + n2 : n1);
string[] newNames = nonArrayString.Split(' ');
David Hedlund’s technique is still far better because it’s easier to read! There are no bonus points for writing the most complicated answer... lol

Categories

Resources