Package 3 chars of Array into an integer C# - c#

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]);
...

Related

Setting int using for loop in one line?

I'm interested in doing something like this (C#):
int sum = 0;
for (int i = 0; i < 5; i++)
sum += i;
But I would like to do it on one line. Something like:
int sum = (embedded loop)
Is there any way to do this on one line? I'm looking to apply this to a more complex string manipulation algorithm so I can't simply replace the loop with an arithmatic formula.
So you want to loop and do something in one line?
First off, writing it in one line isn't going to make it run faster. You are still going to loop, you are still going to be O(n). For the particular problem you have in your question you can do something like:
var sum = Enumerable.Range(0,5).Sum();
This will basically make a collection of the numbers 0,1,2...4 and sum them.
More generally, since you want to do something, you might use the Aggregate function. For example:
var str = Enumerable.Range(0,5).Aggregate("",(p,c) => p + c); // Note: not efficient at all
Will take the values 0,1,...4 and do string concatenation with them (using a string builder would be better) to give you the string 01234.
Edit:
I'm trying to loop through a list of words and make each one title case, then return the string[].join(" ") of it
In that case, something like:
var result = string.Join(" ", myListOfWords.Select(w => char.ToUpper(w[0]) + w.Substring(1)));
Should work fine.
If you don't mind that 'sum' only is in scope of the for loop you could do this:
for (int i = 0, sum = 0; i < 5; sum += i, ++i) { // do something }
for(int i=0,sum = 0; i<5; sum+=i,++i){}

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!

Generate all Permutations of text from a regex pattern in C#

So i have a regex pattern, and I want to generate all the text permutations that would be allowed from that pattern.
Example:
var pattern = "^My (?:biological|real)? Name is Steve$";
var permutations = getStringPermutations(pattern);
This would return the list of strings below:
My Name is Steve
My real Name is Steve
My biological Name is Steve
Update:
Obviously a regex has an infinate number of matches, so i only want to generate off of optional string literals as in the (?:biological|real)? from my example above. Something like (.)* has too many matches, so I will not be generating them off of that.
If you restrict yourself to the subset of regular expressions that are anchored at both ends, and involve only literal text, single-character wildcards, and alternation, the matching
strings should be pretty easy to enumerate. I'd probably rewrite the regex as a BNF grammar
and use that to generate an exhaustive list of matching strings. For your example:
<lang> -> <begin> <middle> <end>
<begin> -> "My "
<middle> -> "" | "real" | "biological"
<end> -> " name is Steve"
Start with the productions that have only terminal symbols on the RHS, and enumerate
all the possible values that the nonterminal on the LHS could take. Then work your
way up to the productions with nonterminals on the RHS. For concatenation of nonterminal symbols, form the Cartesian product of the sets represented by each RHS nonterminal.
For alternation, take the union of the sets represented by each option. Continue
until you've worked your way up to <lang>, then you're done.
However, once you include the '*' or '+' operators, you have to contend with infinite
numbers of matching strings. And if you also want to handle advanced features like backreferences...you're probably well on your way to something that's isomorphic
to the Halting Problem!
One method that might be a bit weird would be to put the possible choices into an array first, and then generate the regex based on the array and then use the same array to generate the permutations.
Here's a sketch of a function I wrote to take a List of Strings and return a list of all the permutated possibilities: (taking on char from each)
public static List<string> Calculate(List<string> strings) {
List<string> returnValue = new List<string>();
int[] numbers = new int[strings.Count];
for (int x = 0; x < strings.Count; x++) {
numbers[x] = 0;
}
while (true) {
StringBuilder value = new StringBuilder();
for (int x = 0; x < strings.Count; x++) {
value.Append(strings[x][numbers[x]]);
//int absd = numbers[x];
}
returnValue.Add(value.ToString());
numbers[0]++;
for (int x = 0; x < strings.Count-1; x++) {
if (numbers[x] == strings[x].Length) {
numbers[x] = 0;
numbers[x + 1] += 1;
}
}
if (numbers[strings.Count-1] == strings[strings.Count-1].Length)
break;
}
return returnValue;
}

Categories

Resources