I have a personal ID and an Industry ID that I would like to compare with each other, but the industry number has zeros and an alphabet character in front. and some numbers are longer than others.
ex.
Personal Number | Industry Number
123 | J000123
1234 | L001234
12345 | M012345
I know how to solve the problem if it was ONLY zeros. Character throws me around, how would I achieve this?
i assume PersonalNumber is a Int and IndustryNumber is has type String
bool Result = int.Parse(string.Concat(PersonalNumber.Skip(1))) == IndustryNumber;
For the updated question (i.e. industry number starts with arbitrary letter followed by a number padded by zeros) it could be
// Remove 1st letter, than remove zeros
String number = IndustryNumber.Substring(1).TrimStart('0');
if (number.Equals(personalNumber)) {
...
}
Use RegEx:
var numb = int.Parse(RegEx.Match(industryNumber, #"\d+^").Value);
//Then compare the two ints
Create a function for given code below
string a = "str123";
string b = string.Empty;
int val;
for (int i=0; i< a.Length; i++)
{
if (Char.IsDigit(a[i]))
b += a[i];
}
if (b.Length>0)
val = int.Parse(b);
then call getInt(mystring)==int
by Dominik answer
Regex.Replace("J0123", "([A-z]*)", "");
You can use a Regex to remove the first part of the Industry number:
Regex.Replace("J0123", "J0*", "");
results in "123"
UPDATE, to account for all letters use this regex:
Regex.Replace("J0123", "[A-Z]0*", "");
You need to use substring() on the Industry Number and Convert after:
I assume you use an array of string with 2 dimensions. string[,] myarray.
for (int i = 0; i<myarray.GetLengh(0);i++)
{
//get personnal number as integer, this is simple
int personnal = Convert.ToInt32(myarray[i][0]);
//get industry number as integer, this is the difficult part
string strIndustry = myarray[i][1];
strIndustry = strIndustry.SubString(0,1);//remove the first char
int industry = Convert.ToInt32(strindustry);//I assume that you only have numbers after the letter if not you may need to test it with tryParse...
//then you can now compare integers
if(personnal==industry)
{
//your code to execute if true
}
else{//...}
}
Assuming you have two arrays for PersonalId and IndustryID.Result is another array to which will hold the result.
for(int i=0; i< PersonalID.Count i++)
{
if(IndustryID[i].Contains(PersonalID[i]))
{
Result[i]=true;
}
else
Result[i]=False;
}
Related
I want the user to first type a code (e.g. fkuk3463kj)
The array is limited to 20.
The rest must be filled with fillers.
Which filler the customer will use (e.g. #, t, z,7,_,0) is his own choice and he will asked to define it at the beginning right after the question for the code.
(hint: afterwards (or if possible directly) I have to decide (to complete the wish of customer) whether the filler has to be at the beginning or at the end.
(for example: fkuk3463kj########## or ##########fkuk3463kj)
Now I don't know how to implement this. I know, that it's not that difficult, but I don't get it! All my tryings were not really succesful.
Could anybody help me? This would be perfect!
And many thx in advance!
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
string[] CNr = new string[companyNr.Length];
Console.WriteLine("Type a filler");
string filler= Convert.ToString(Console.ReadLine());
string[] fill = new string[filler.Length];
.
.
.
.
.
(please pardon my english...)
As far as I can see, you're working with string:
// Trim: let's trim off leading and trailing spaces: " abc " -> "abc"
string companyNr = Console.ReadLine().Trim();
which you want to Pad with some char up to the length length (20 in your case):
int length = 20;
string filler = Console.ReadLine().Trim();
// padding character: either provided by user or default one (#)
char pad = string.IsNullOrEmpty(filler) ? '#' : filler[0];
// shall we pad left: "abc" -> "##abc" or right: "abc" -> "abc##"
// I have to decide (to complete the wish of customer)
//TODO: whether the filler has to be at the beginning or at the end
bool leftPad = true;
string result = leftPad
? companyNr.PadLeft(length, pad)
: companyNr.PadRight(length, pad);
// in case you want a char array
char[] array = result.ToCharArray();
// in case you want a string array
string[] strArray = result.Select(c => c.ToString()).ToArray();
Since you are getting strings as an input you can use string padding. Look here: Padding Strings in the .NET Framework
You can write some method (or extension method):
string AppendString(string str, int count, char filler, bool fromStart)
{
return fromStart ? str.PadLeft(count, filler) : str.PadRight(count, filler);
}
I think this code should work for you.
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
Console.WriteLine("Type a filler");
string filler= Convert.ToChar(Console.ReadLine());
string fill = companyNr.PadLeft(20,filler);
// or use string fill = companyNr.PadRight(20,filler);
Welcome to StackOverflow. I am also a beginner :)
int fixedLength = 20;
string mockupInput = "bladjiea";
string filler = "-";
While(mockupInput.Length < fixedLength)
{
mockupInput += filler;
}
This is easy beginner code that should work.
Lets make this a contest on who will write most beautiful code:
I'll start with the most trivial, brute method XD.
If you have the number:
int fillLength = 20 - companyNr.Length; //for example, 20 chars total.
You can fill a StringBuilder in a loop:
var sb = new StringBuilder()
for (int c = 0; c < fillLength; c++)
sb.Append(filler);
string result = companyNr + sb.ToString();
I need to covert this string strRX="16 255 128" to a string with Hex values strTX="10 FF 80.." as a string.
Meaning somehow before I printing this, the string I'm going to send must change its value.
string strRX="16 255 128";
string strTX = string.Join(" ",strRX.Split().Select(rx => Convert.ToByte(rx).ToString("X")));
There are two problems to solve here.
Parse a space-separated string of integers rendered in decimal format, into an array of integers.
Render an array of integers as a space separated string of integers rendered in hexadecimal format.
First we split the string into an array of strings, one for each integer. Then we create somewhere to store the parsed integers, and then we process each of them preserving the order. Finally we construct the output string
string strRX = "16 255 128";
string[] ss = strRX.Split(' ');
Now we have to parse each as an integer.
int[] ii = new int[ss.Length];
for (int i = 0; i< ss.Length; i++)
{
ii[i] = int.Parse(ss[i]);
}
Next we render each integer as a hexadecimal string. I could create new storage for the output but I'm going to simply write over the top of the input strings. Sample output is ambiguous, but ancient convention shows bytes with leading zeroes in hex, so the format specifier is X2.
for (int i = 0; i < ss.Length; i++)
{
ss[i] = ii[i].ToString("X2");
}
Obviously you can do this in the same loop.
int[] ii = new int[ss.Length];
for (int i = 0; i < ss.Length; i++)
{
ii[i] = int.Parse(ss[i]);
ss[i] = ii[i].ToString("X2");
}
And you don't need to keep them all in an array if you finish with them immediately, so you can collapse it further.
for (int i = 0; i < ss.Length; i++)
{
ss[i] = int.Parse(ss[i]).ToString("X2");
}
At this point you can put it all back together.
string strTX = string.Join(" ", ss);
And here's all of it at once.
string strRX = "16 255 128";
string[] ss = strRX.Split(' ');
for (int i = 0; i < ss.Length; i++)
{
ss[i] = int.Parse(ss[i]).ToString("X2");
}
string strTX = string.Join(" ", ss);
But that's clunky. You can express the whole thing far more elegantly as a set operation.
string strRX = "16 255 128";
string strTX = string.Join(" ", strRX.Split().Select(rx => int.Parse(rx).ToString("X2")));
How does that work?
strRX.Split() takes an array of separators and returns an array of strings. From Cetin we learn that when the array of separators is empty the string is split on whitespace.
The LINQ Select method can be applied to any IEnumerable which includes arrays.
rx => int.Parse(rx).ToString("X2")) defines a lambda expression, which is a kind of inline anonymous function, which in this case the function takes a parameter rx and returns the value of int.Parse(rx).ToString("X2").
The Select method returns the array produced be calling this function on each element of the array of strings and assembling the returned values into another array.
string.Join(" ", X) assembles a string from the elements of X separated by spaces.
And now, a word from our sponsor... (only kidding).
Cetin suggests in the comments that I should mention how handy Linqpad is for interactively testing and refining this sort of expression.
As it happens I too am a bit of a Linqpad fan.
I my application due to some reason I have two numbers in 5 digits.
The following code give you brief idea.
string s = "00001"; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + s;
//Operation end
//Increment the value of s by 1. i.e 00001 to 00002
This can be done easily by convert the value of s to int and increment it by 1 but after all that I have to also store the incremented value of s in 5 digit so it will be "00002".
This think give me a pain...
use
string s = "00001";
int number = Convert.ToInt32(s);
number += 1;
string str = number.ToString("D5");
to get atleast 5 digits.
The "D" (or decimal) format specifier
If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no
precision specifier is specified, the default is the minimum value
required to represent the integer without leading zeros.
This seems to work for me.
string s = "00001";
int i = Int32.Parse(s);
i++;
s = i.ToString("D" + s.Length);
So I think you want to know how to convert an int to a 5 digit string.
You can do this:
int i = 1;
string s = i.ToString("D5");
//s = "00001"
There are plenty of format examples here.
Use String.Format() to achieve this:
string str = String.Format({0:#####}, s);
Look here.
This works using the PadLeft function:
int i = 1; // Initially stored somewhere.
//Operation start
string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + i.ToString().PadLeft(5, '0');
//Operation end
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;
Suppose I have a string "011100011".
Now I need to find another string by adding the adjacent digits of this string, like the output string should be "123210122".
How do I split each characters in the string and manipulate them?
The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.
But can you suggest some simpler methods?
Here's a solution which uses some LINQ plus dahlbyk's idea:
string input = "011100011";
// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0";
var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
output += integers.Skip(i).Take(3).Sum();
}
// output is now "123210122"
Please note:
the code is not optimized. E.g. you might want to use a StringBuilder in the for loop.
What should happen if you have a '9' in the input string -> this might result in two digits in the output string.
Try converting the string to a character array and then subtract '0' from the char values to retrieve an integer value.
string input = "011100011";
int current;
for (int i = 0; i < input.Length; i ++)
{
current = int.Parse(input[i]);
// do something with current...
}