Compare a string row - c#

Let´s say that I have a string that looks like this:
string WidthStr= "0086;0086;0086;0086;0086;0086;0086;0086;0085;";
And then i´m picking up the first number:
FirstRollWidthStr = WidthPadLeft.Substring(0, 4);
The question I have is: Is it possible to compare the data i that i got from the row below (FirstRollWidthStr = WidthPadLeft.Substring(0, 4);) with the rest?
So from FirstRollWidthStr = WidthPadLeft.Substring(0, 4); i got: 0086. And there are more numbers in string WidthStr, and the last number are 0085 so it´s different from 0086 so i want to pick up the numbers who are different from the first number.

var numbers = WidthStr.Split(';').Select(double.Parse).Distinct().ToArray();
Or if you need only numbers different from the first one then (continuing previous code):
var otherNumbers = numbers.Skip(1).Except(numbers.Take(1));

Try this:
var numbers = WidthStr.Split(';');
if(numbers.Length > 0)
{
var differentNumbers = numbers.Skip(1).Where(x => x != numbers[0]);
// ...
}

Related

I need to run command that in string

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

How to take digits from two different numbers and form a new one

I have the following problem here:My input is several lines of 2 digit numbers and I need to make a new number using the second digit of the first number and the first of the next one.
Example:
int linesOfNumbers = Convert.ToInt32(Console.ReadLine());
for(int i = 0,i<linesOfNumbers,i++)
{
int numbers = Conver.ToInt32(Console.ReadLine());
//that's for reading the input
}
I know how to separate the numbers into digits.My question is how to merge them.
For example if your input is 12 and 21 the output should be 22.
I like oRole's answer, but I think they're missing a couple things with the example input that you provided in your comment. I'll also point out some of the errors in the code that you have.
First off, if you're only given the input 12,23,34,45, then you don't need to call Console.ReadLine within your for loop. You've already gotten the input, you don't need to get any more (from what you've described).
Secondly, unless you're doing mathematical operations, there is no need to store numerical data as ints, keep it as a string, especially in this case. (What I mean is that you don't store Zip Codes in a database as a number, you store it as a string.)
Now, onto the code. You had the right way to get your data:
var listOfNumbers = Console.ReadLine();
At that point, listOfNumbers is equal to "12,23,34,45". If you iterate on that variable as a string, you'll be taking each individual character, including the commas. To get each of the numbers to operate on, you'll need to use string.Split.
var numbers = listOfNumbers.Split(',');
This turns that list into four different two character numbers (in string form). Now, you can iterate over them, but you don't need to worry about converting them to numbers as you're operating on the characters in each string. Also, you'll need a results collection to put everything into.
var results = new List<string>();
// Instead of the regular "i < numbers.Length", we want to skip the last.
for (var i = 0; i < numbers.Length - 1; i++)
{
var first = numbers[i];
var second = numbers[i + 1]; // This is why we skip the last.
results.Add(first[1] + second[0]);
}
Now your results is a collection of the numbers "22", "33", and "44". To get those back into a single string, you can use the helper method string.Join.
Console.WriteLine(string.Join(",", results));
You could use the string-method .Substring(..) to achieve what you want.
If you want to keep int-conversion in combination with user input, you could do:
int numA = 23;
int numB = 34;
int resultAB = Convert.ToInt16(numA.ToString().Substring(1, 1) + numB.ToString().Substring(0, 1));
Another option would be to take the users input as string values and to convert them afterwards like that:
string numC = "12";
string numD = "21";
int resultCD = Convert.ToInt16(numC.Substring(1, 1) + numD.Substring(0, 1));
I hope this code snippet will help you combining your numbers. The modulo operator (%) means: 53 / 10 = 5 Rest 3
This example shows the computation of the numbers 34 and 12
int firstNumber = 34 - (34 % 10) // firstNumber = 30
int secondNumber = 12 % 10; // secondNumber = 2
int combined = firstNumber + secondNumber; // combined = 32
EDIT (added reading and ouput code):
boolean reading = true;
List<int> numbers = new ArrayList();
while(reading)
{
try
{
int number = Convert.ToInt32(Console.ReadLine());
if (number > 9 && number < 100) numbers.Add(number);
else reading = false; // leave reading process if no 2-digit-number
}
catch (Exception ex)
{
// leave reading process by typing a character instead of a number;
reading = false;
}
}
if (numbers.Count() > 1)
{
List<int> combined = new ArrayList();
for (int i = 1; i <= numbers.Count(); i++)
{
combined.Add((numbers[i-1] % 10) + (numbers[i] - (numbers[i] % 10)));
}
//Logging output:
foreach (int combination in combined) Console.WriteLine(combination);
}
As you mention, if you already have both numbers, and they are always valid two digit integers, following code should work for you.
var num1 = 12;
var num2 = 22;
var result = (num2 / 10)*10 + (num1 % 10);
num2/10 returns the first digit of second number, and num1 % 10 returns the second digit of the first number.
The % and / signs are your savior.
If you want the 'ones' digit of a number (lets call it X), simply do X%10 - the remainder will be whatever number is in the 'ones' digit. (23%10=3)
If, instead, the number is two digits and you want the 'tens' digit, divide it by ten. (19/10=1).
To merge them, multiply the number you want to be in the 'tens' digit by ten, and add the other number to it (2*10+2=22)
There are other solutions like substring, etc and many one have already given it above. I am giving the solution VIA LINQ, note that this isn't efficient and it's recommended only for learning purpose here
int numA = 12;
int numB = 21 ;
string secondPartofNumA = numA.ToString().Select(q => new string(q,1)).ToArray()[1]; // first digit
string firstPartofNumB = numB.ToString().Select(q => new string(q,1)).ToArray()[0]; // second digit
string resultAsString = secondPartofNumA + firstPartofNumB;
int resultAsInt = Convert.ToInt32(resultAsString);
Console.WriteLine(resultAsString);
Console.WriteLine(resultAsInt);

Autogenerated number with the use of date and time c#

Having trouble on how am i going to autogenerate a number with the use of date and time. For example, i need to generate this kind of number, 16-9685 with, 16 = year and 9685 be randomized and will be shown in a textbox. i tried this one but unfortunately, this doesn't work. thanks for helping
var random = new Random(System.DateTime.Now.Year);
int randomNumber = random.Next(-1000, -1);
TextBoxSESID.Text = randomNumber.ToString();
// Keep this _r as a member, not local
Random _r = new Random();
...
// Gen a random number
int rand = _r.Next(1, 10000);
// Get the "2016-" prefix
string yearPrefix = DateTime.Now.Year + "-";
// Remove the first 2 digits of the year prefix, now it is "16-"
yearPrefix = yearPrefix.Substring(2);
// Put the year prefix together with the random number into the textbox
TextBoxSESID.Text = yearPrefix + rand;
I'm going to suggest that this is a nice clean way to produce the string you require:
TextBoxSESID.Text = $"{DateTime.Now.Year % 100}-{_r.Next(1, 10000)}";
If you're not using C# 6 then this will work too:
TextBoxSESID.Text = String.Format("{0}-{1}", DateTime.Now.Year % 100, _r.Next(1, 10000));
You still need have this as a field:
private Random _r = new Random();
If you want to ensure that no two names are repeated (assuming that you never use more than 9,999 names) then do this:
File.WriteAllLines(
"16.txt",
Enumerable
.Range(1, 9999)
.Select(n => $"{DateTime.Now.Year % 100}-{n}")
.OrderBy(x => _r.Next()));
Now you have a file that has all the possible numbers in a random order.
To get a new number do this:
var lines = File.ReadAllLines("16.txt");
var first = lines.First();
File.WriteAllLines("16.txt", lines.Skip(1));
It will take the top line and re-save the file without it.
Just make sure you create files for each year as it comes along.

How to pick one random string from given strings?

How can I make a program that will pick one random string from given strings like this:
int x;
x = Random.Range(0,2);
string[] Quest0 = {"You","Are","How","Hello"};
string[] Quest1 = {"Hey","Hi","Why","Yes"};
string[] Quest2 = {"Here","Answer","One","Pick"};
I would like to print out like this:
if x = 2 it would print out Quest2 and so on.
Thank you!
List<String[]> quests = new ArrayList<String[]>();
quests.add(0, new string[]{"You","Are","How","Hello"});
quests.add(1, new string[]{"Hey","Hi","Why","Yes"});
quests.add(2, new string[]{"Here","Answer","One","Pick"});
int x = new Random().nextInt((2 - 0) + 1);
System.out.println(quests.get(x).toString());
Fistly you need to declare a random variable.
Random random = new Random();
this will create a variable in which you can now get random numbers from. to get random numbers you will use random.next(x,y) or in your case random.next(0,3) because the final argument is exclusive, so if you want 0, 1 or 2, you must use (0,3).
you then need to make some conditional statments, i would use If statments, to accomplish your goal use something like this:
if (x == 2)
{
foreach (string s in Quest2)
{
Console.WriteLine(s);
}
}
Do this for each possible outcome and it will print out all of the values in your array of strings. Hope I have been helpful, thanks.
Also if you new become familiar with these links:
http://msdn.microsoft.com/en-us/library/system.random%28v=vs.110%29.aspx
http://msdn.microsoft.com/en-gb/library/aa288453%28v=vs.71%29.aspx

How can I count the numbers in a string of mixed text/numbers

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

Categories