c# padding to string - c#

Am reading from an excel sheet column and need to save into an sql table.
this is what the fiedl looks like in excel;'33349836', but I need it to be saved this way in the database '0033349836', because that field needs to be 10characters.

You can use String.PadLeft Method (Int32, Char) overload.
Returns a new string that right-aligns the characters in this instance
by padding them on the left with a specified Unicode character, for a
specified total length.
string s = "33349836";
string newstring = s.PadLeft(10, '0');
Remember, 0033349836 will be a string representation of your numeric values. Don't keep this kind of data in a numeric column type. Keep it in a some character type of column like nvarchar.

There are a couple of ways to do this using C#.
One such way is this:
static void Main(string[] args)
{
string s = "33349836";
int width = 10;
char padding = '0';
string s1 = s.PadLeft(width, padding);
Console.WriteLine(s);
Console.WriteLine(s1);
}
That code will output these values:
33349836
0033349836

You can use PadLeft() function to add zeros to your string.
Try This:
var str = "33349836";
str = str.PadLeft(10,'0');

Related

How to get the char from a string that contains unicode escape sequence which starts with "\u"

I did quite a lot of researches but still could not figure it out. Here is an example, I got a string contains "\uf022" (a character from another language), how can I change the whole string into the char '\uf022'?
Update:
the string "\uf022" is retrieved during runtime (read from other sources) instead of directly putting a static character into the string.
For example:
string url = "https://somesite/files/abc\uf022def.pdf";
int i = url.IndexOf("\\");
string specialChar = url.substring(i, 6);
How do I get the char saved in the string specialChar?
I would like to use this char to do UTF-8 encoding and generate the accessible URL "https://somesite/files/abc%EF%80%A2def.pdf".
Thank you!
how can I change the whole string into the char '\uf022'?
Strictly speaking, you can't change the characters of the string you have (because strings are immutable), but you can make a new one that meets your demands..
var s = new string('\uf022', oldstring.Length);
Your title of your question reads slightly differently.. it sounds like you want a string that is only the F022 chars, i.e. if your string has 10 chars and only 3 of them are F022, you want just the 3.. which could be done by changing oldstring.Length above, into oldstring.Count(c => c == '\uf022')
..and if you mean your string is like "hello\uf022world" and you want it to be like "hello🍄world" then do
var s = oldstring.Replace("\\uf022", "\uf022");
If you have the \uf022 in a string (6 chars) and you want to replace it with its actual character, you can parse it to int and convert to char when you replace..
var oldstring = "hello\uf022world";
var given = "\uf022";
var givenParsed = ((char)Convert.ToInt32(given.Substring(2), 16)).ToString();
var s = oldstring.Replace(given, givenParsed);

String with index conversion or array of numbers

Why i can't convert this string to a number? Or how to make a array of numbers from this string.
string str = "110101010";
int c = Int32.Parse(str[0]);
str is a string so str[0] returns a char and the Parse method doesnt take a char as input but rather a string.
if you want to convert the string into an int then you would need to do:
int c = Int32.Parse(str); // or Int32.Parse(str[0].ToString()); for a single digit
or you're probably looking for a way to convert all the individual numbers into an array which can be done as:
var result = str.Select(x => int.Parse(x.ToString()))
.ToArray();
I assume you are trying to convert a binary string into its decimal representation.
For this you could make use of System.Convert:
int c = Convert.ToInt32(str, 2);
For the case that you want to sum up all the 1s and 0s from the string you could make use of System.Linq's Select() and Sum():
int c = str.Select(i => int.Parse(i.ToString())).Sum();
Alternatively if you just want to have an array of 1s and 0s from the string you could omit the Sum() and instead enumerate to an array using ToArray():
int[] c = str.Select(i => int.Parse(i.ToString())).ToArray();
Disclaimer: The two snippets above using int.Parse()would throw an exception if str were to contain a non-numeric character.
Int32.Parse accepts string argument, not char which str[0] returs.
To get the first number, try:
string str = "110101010";
int c = Int32.Parse(str.Substring(0, 1));

Get only numbers from line in file

So I have this file with a number that I want to use.
This line is as follows:
TimeAcquired=1433293042
I only want to use the number part, but not the part that explains what it is.
So the output is:
1433293042
I just need the numbers.
Is there any way to do this?
Follow these steps:
read the complete line
split the line at the = character using string.Split()
extract second field of the string array
convert string to integer using int.Parse() or int.TryParse()
There is a very simple way to do this and that is to call Split() on the string and take the last part. Like so if you want to keep it as a string:
var myValue = theLineString.Split('=').Last();
If you need this as an integer:
int myValue = 0;
var numberPart = theLineString.Split('=').Last();
int.TryParse(numberPart, out myValue);
string setting=sr.ReadLine();
int start = setting.IndexOf('=');
setting = setting.Substring(start + 1, setting.Length - start);
A good approach to Extract Numbers Only anywhere they are found would be to:
var MyNumbers = "TimeAcquired=1433293042".Where(x=> char.IsDigit(x)).ToArray();
var NumberString = new String(MyNumbers);
This is good when the FORMAT of the string is not known. For instance you do not know how numbers have been separated from the letters.
you can do it using split() function as given below
string theLineString="your string";
string[] collection=theLineString.Split('=');
so your string gets divided in two parts,
i.e.
1) the part before "="
2) the part after "=".
so thus you can access the part by their index.
if you want to access numeric one then simply do this
string answer=collection[1];
try
string t = "TimeAcquired=1433293042";
t= t.replace("TimeAcquired=",String.empty);
After just parse.
int mrt= int.parse(t);

padding in asp.net

Is there a function to append padding digits to the left of a digit.I want to form a 3 digit number, so when the value is '3' i need to make it '003'
e.g in php we have
$m_ccode=str_pad($m_casecode,3,"0",str_pad_left);
same i want to convert in asp.net c#. How can i do it, i have numeric value stored in string 's'
String s = DropDownList3.SelectedItem.Value;
string variant1 = "3".PadLeft(3, '0'); // if you have a string
string variant2 = 3.ToString("000"); // if you have a number
In your case you need to unbox your int if the numeric value is an int
String s = ((int)DropDownList3.SelectedItem.Value).ToString("000");
Try the following:
String s = DropDownList3.SelectedItem.Value.PadLeft(3, '0');

How to delete characters and append strings?

I am adding a new record to XML file, first I'm querying all existing items and storing the count in an int
int number = query.count()
and then increment the number by 1.
number = number + 1;
Now I want to format this value in a string having N00000000 format
and the number will occupy the last positions.
Pseudo code:
//declare the format string
sting format = "N00000000"
//calculate the length of number string
int length =number.ToString().Length();
// delete as many characters from right to left as the length of number string
???
// finally concatenate both strings with + operator
???
String output = "N" + String.Format ("00000000", length)
Alternatively if you change your formatstring to "'N'00000000" you can even use:
String output = String.Format (formatString, length)
Which means you can fully specify your output by changing your formatstring without having to change any code.
int i = 123;
string n = "N" + i.ToString().PadLeft(8, '0');
var result = number.ToString("N{0:0000000}");
HTH
You can use the built in ToString overload that takes a custom numeric format string:
string result = "N" + number.ToString("00000000");
Here is a another one ...
result = String.Format("N{0:00000000}",number);

Categories

Resources