This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5
Related
This question already has answers here:
Natural Sort Order in C#
(18 answers)
Closed 2 years ago.
I have an example string:
"60 seconds,1;120 seconds,2;180 seconds,3;15 seconds,15;20 seconds,20;30 seconds,30"
I'd like to sort it by the first number only. So after sorting, it'll look like:
"15 seconds,15;20 seconds,20;30 seconds,30;60 seconds,1;120 seconds,2;180 seconds,3"
Some limitations:
I can't hard code anything. I've created example code to demonstrate my solution so far.
Basically, I create 2 string arrays and 1 int array. The first string array takes the string and splits it by the semicolon. The second string array is a middle man array. The int array is the middle man array converted to int. I use the int array as a reference to sort my first string array using Array.sort
Here is my example code:
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string myExampleString = "60 seconds,1;120 seconds,2;180 seconds,3;15 seconds,15;20 seconds,20;30 seconds,30";
string mySortedString = "";
// Count the number of semicolons and + 1 to get arraySize
int arraySize = myExampleString.Count(f => (f == ';')) + 1;
// To hold our original string, split by the ';'
String[] stringArray = new String[arraySize];
// Our middle man array to make sorting easier
String[] organizedStringArray = new String[arraySize];
// Our middle man array converted to int
int[] intArray = new int[arraySize];
// Create the stringArray without the semicolons
stringArray = myExampleString.Split(';');
for(int i=0; i<arraySize; i++)
{
// Our stringArray elements:
/*
60 seconds,1
120 seconds,2
180 seconds,3
15 seconds,15
20 seconds,20
30 seconds,30
*/
// Let's make our organizedStringArray elements:
/*
60
120
180
15
20
30
*/
Regex regex = new Regex(" .*");
organizedStringArray[i] = regex.Replace(stringArray[i], "");
}
// Convert the middleman array to ints
intArray = Array.ConvertAll(organizedStringArray, s => int.Parse(s));
// Use the sort function to sort our orignal stringArray, using intArray as the reference
Array.Sort(intArray, stringArray);
// Append the results into mySortedString
for(int i=0; i<arraySize; i++)
{
if(i < arraySize - 1 )
{
mySortedString += stringArray[i] + ";";
}
else
{
mySortedString += stringArray[i];
}
}
Console.WriteLine(mySortedString);
}
}
You could use Linq to do a lot of the heavy lifting. I'd split the string by ; to get an array, then sort this array with a custom comparer that splits the string by ' ', takes the first part and parses it to an int, and then join that array back with ;s:
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string myExampleString = "60 seconds,1;120 seconds,2;180 seconds,3;15 seconds,15;20 seconds,20;30 seconds,30";
string sorted = String.Join(";", myExampleString.Split(';').OrderBy(s => int.Parse(s.Split(' ')[0])));
Console.WriteLine(sorted);
}
}
I have a problem with code.
I want to implement radix sort to numbers on c# by using ling.
I give as input string and give 0 in the start of the number:
foreach(string number in numbers){<br>
if(number.lenth > max_lenth) max_lenth = number.lenth;<br><br>
for(int i = 0; i < numbers.lenth; i++){<br>
while(numbers[i].length < max_lenth) numbers[i] = "0" + numbers[i];<br><br>
after this I need to order by each number in string, but it doesn't work with my loop:
var output = input.OrderBy(x => x[0]);
for (int i = 0; i < max_lenth; i++)
{
output = output.ThenBy(x => x[i]);
}
so I think to create a string that contain "input.OrderBy(x => x[0]);" and add "ThenBy(x => x[i]);"
while max_length - 1 and activate this string that will my result.
How can I implement it?
I can't use ling as a tag because its my first post
If I am understanding your question, you are looking for a solution to the problem you are trying to solve using Linq (by the way, the last letter is a Q, not a G - which is likely why you could not add the tag).
The rest of your question isn't quite clear to me. I've listed possible solutions based on various assumptions:
I am assuming your array is of type string[]. Example:
string[] values = new [] { "708", "4012" };
To sort by alpha-numeric order regardless of numeric value order:
var result = values.OrderBy(value => value);
To sort by numeric value, you can simply change the delegate used in the OrderBy clause assuming your values are small enough:
var result = values.OrderBy(value => Convert.ToInt32(value));
Let us assume though that your numbers are arbitrarily long, and you only want the values in the array as they are (without prepending zeros), and that you want them sorted in integer value order:
string[] values = new [] { "708", "4012" };
int maxLength = values.Max(value => value.Length);
string zerosPad = string
.Join(string.Empty, Enumerable.Repeat<string>("0", maxLength));
var resultEnumerable = values
.Select(value => new
{
ArrayValue = value,
SortValue = zerosPad.Substring(0, maxLength - value.Length) + value
}
)
.OrderBy(item => item.SortValue);
foreach(var result in resultEnumerable)
{
System.Console.WriteLine("{0}\t{1}", result.SortValue, result.ArrayValue);
}
The result of the above code would look like this:
0708 708
4012 4012
Hope this helps!
Try Array.Sort(x) or Array.Sort(x,StringComparer.InvariantCulture).
This question already has answers here:
Convert char to int in C#
(20 answers)
Closed 4 years ago.
This question is different as it tackles the issue of converting a char to an int when adding to an integer array.
The following piece of code, I am trying to implement a string of integers into a int[] array in C#.
My desired output is an array of:
12345678910
This is my code, however, the output of this is not what I desire:
string numbers = "12345678910";
int[] array = new int[numbers.Length];
for (int i = 1; i <= numbers.Length; i++)
{
array[i - 1] = numbers[i-1];
}
foreach(var y in array)
{
Console.Write(y);
}
Output of given code:
4950515253545556574948
Can somebode tell me why I am getting this output, and what I can do to fix this? Thank you!
Edit: Changed my code and it works using this:
for (int i = 0; i < numbers.Length; i++)
{
array[i] = int.Parse(numbers[i].ToString());
}
First of all, I don't think you'll be able to distinguish a two digit number using this method.
I refer to this part of your code: string numbers = "12345678910";
Iterate through your string characters and parse to Int (if that's what's required) (credit) (credit)
foreach (char character in yourString)
{
int x = (int)Char.GetNumericValue(character);
//code to add to your array of ints
}
This question already has answers here:
Iterate two Lists or Arrays with one ForEach statement in C#
(12 answers)
Closed 8 years ago.
I have 2 array
string[] Namesvalues = Names.Split(',');
string[] TotalValues = Total.Split(',');
Above both arrays have exactly equal values.what i want to do is to iterate above two arrays in parallel and want to get one by one value from both arrays.
Can any one tell me how can i do that??
You could simply use a for-loop:
for(int i = 0; i < NamesValues.Length; i++)
{
string name = NamesValues[i];
string totalValue = TotalValues[i];
}
If the length is different you could use ElementAtOrDefault:
for(int i = 0; i < Math.Max(NamesValues.Length, TotalValues.Length) ; i++)
{
string name = NamesValues.ElementAtOrDefault(i);
string totalValue = TotalValues.ElementAtOrDefault(i);
}
You also could use Enumerable.Zip to create an anonymous type with both values:
var namesAndValues = NamesValues.Zip(TotalValues,
(n, tv) => new { Name = n, TotalValue = tv });
foreach(var nv in namesAndValues)
{
Console.WriteLine("Name: {0} Value: {1}", nv.Name + nv.TotalValue);
}
Note that the second approach using a for-loop and ElementAtOrDefault is different to to the Enumerable.Zip approach.
The former iterates both arrays completely and ElementAtOrDefault returns null for the value of the smaller array if there is no element at that index.
The latter Zip combines elements only until it reaches the end of one of the sequences.
So when you use Math.Min instead of Math.Max in the for-loop you get a similar behaviour, but then you should use the first approach anyway since there's no need for ElementAtOrDefault.
//exactly equal length
for (int i = 0; i < Namesvalues.Length; i++)
{
var name = Namesvalues[i];
var total = TotalValues[i];
}
So what I'm trying to do, is take a job number, which looks like this xxx123432, and count the digits in the entry, but not the letters. I want to then assign the number of numbers to a variable, and use that variable to provide a check against the job numbers to determine if they are in a valid format.
I've already figured out how to perform the check, but I have no clue how to go about counting the numbers in the job number.
Thanks so much for your help.
Using LINQ :
var count = jobId.Count(x => Char.IsDigit(x));
or
var count = jobId.Count(Char.IsDigit);
int x = "xxx123432".Count(c => Char.IsNumber(c)); // 6
or
int x = "xxx123432".Count(c => Char.IsDigit(c)); // 6
The difference between these two methods see at Char.IsDigit and Char.IsNumber.
Something like this maybe?
string jobId = "xxx123432";
int digitsCount = 0;
foreach(char c in jobId)
{
if(Char.IsDigit(c))
digitsCount++;
}
And you could use LINQ, like this:
string jobId = "xxx123432";
int digitsCount = jobId.Count(c => char.IsDigit(c));
string str = "t12X234";
var reversed = str.Reverse().ToArray();
int digits = 0;
while (digits < str.Length &&
Char.IsDigit(reversed[digits])) digits++;
int num = Convert.ToInt32(str.Substring(str.Length - digits));
This gives num 234 as output if that is what you need.
The other linq/lambda variants just count characters which I think is not completely correct if you have a string like "B2B_MESSAGE_12344", because it would count the 2 in B2B.
But I'm not sure if I understood correctly what number of numbers means. Is it the count of numbers (other answers) or the number that numbers form (this answer).