How to delete characters and append strings? - c#

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

Related

How can I add an integer to an existing record?

Please be kind enough to tell me how I can add an integer to an existing record which starts with a string sequence like the following;
S0000 - S00027
Kind Regards,
Indunil Sanjeewa
Try this code:
string record = "S00009";
string recordPrefix = "S";
char paddingCharacter = '0';
string recordNoPart = record.Substring(recordPrefix.Length);
int nextRecordNo = int.Parse(recordNoPart) + 1;
string nextRecord = string.Format("{0}{1}", recordPrefix, nextRecordNo.ToString().PadLeft(record.Length - recordPrefix.Length, paddingCharacter));
#kurakura88 has already given the logic. I have just provided the hardcore c# code.
The logic is:
separate the "S00009" into "S" and "00009". Use string method Substring()
Parse "00009" into integer. Use Int.Parse or Int.TryParse
Add 1 into the integer
Print back the "S" and the integer. Use string.Concat or simply string + integer
You can use following approach
string input = #"S0000";
string pattern = #"\d+";
string format = #"0000";
int addend = 1;
string result = Regex.Replace(input, pattern,
m => (int.Parse(m.Value) + addend).ToString(format));
// result = S0001
Regular expression \d+ matches all digits.
MatchEvaluator converts matched value to integer. Then adds the addend. Then converts the value to a string using the specified format.
In the end using the Replace method replaces the previous value with the new value.

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

Creating fixed length numeric string

I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: head001.jpg, head002.jpg, head003.jpg etc. etc.
The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - tail00001.jpg, tail00002.jpg, tail00003.jpg etc. until tail00100.jpg
And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5
In C++, I’ve seen this formatting being done as follows:
format <<prefix<<"%0"<<numDigits<<"d."<<filetype; //where format is a stringstream
However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
Just use string.Format, with a precision specifier saying how many digits you want:
string name = string.Format("tail{0:d6}.jpg", index);
See the MSDN documentation for standard numeric string formats for more details.
You can build the string format up programmatically of course:
string name = string.Format("tail{0:d" + digits + "}.jpg", index);
Or use PadLeft as suggested by Vano. You might still want to use string.Format though:
string name = string.Format("tail{0}.jpg",
index.ToString().PadLeft(digits, '0'));
Using PadLeft has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be 0 anyway.
string has PadLeft method:
int n1 = 1;
string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001
int n10 = 10;
string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on...
You can do this using string.Format
var result = string.Format("{0}{1:00000}{2}", prefix, number, filetype)
Or you could use padleft
var result = prefix + number.ToString().PadLeft('0', numDigits) + "." + extension;
Or you can use a mix of the two :)
..and in this case: start digit would be 0, end digit would be 100 and
numDigits would be 5
You could use String.Format and the decimal format/precision specifier "D"` and a for-loop:
int start = 0;
int end = 100;
int numDigits = 5;
string name = "tail";
string extension = ".jpg";
for(int i = start; i <= end; i++)
{
string fileName = string.Format(
"{0}{1}{2}", name, i.ToString("D" + numDigits), extension);
Console.WriteLine(fileName);
}
Outputs:
tail00000.jpg
tail00001.jpg
tail00002.jpg
tail00003.jpg
tail00004.jpg
tail00005.jpg
tail00006.jpg
tail00007.jpg
tail00008.jpg
tail00009.jpg
tail00010.jpg
....
tail100.jpg
For modern .NET 5.0+ (2021 update)
int myint = 100;
string zeroPadded = $"{myint:d8}"; // "00000100"
string spacePadded = $"{myint,8}"; // " 100"

Number increment from string value

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

String operations in 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...
}

Categories

Resources