Add one to C# reference number - c#

My reference number is "DTS00001" it is a String variable in C# program
i want to increment this number by one and the result should be like "DTS00002"
here is the code i tried,
while (reader.Read())
{
String str = reader["rfno"].ToString();
String st = str.Substring(3, 5);
int number = Convert.ToInt32(st);
number += 1;
string myNewString = "DTS" + number;
MessageBox.Show(myNewString);
The result doesn't contain the required leading zeros before the new number.
.

Homework or not, here's one way to do it. It's heavily influensed by stemas answer. It uses Regex to split the alphabetical from the numeric. And PadLeft to maintain the right number of leading zeroes.
Tim Schmelters answer is much more elegant, but this will work for other types of product-numbers as well, and is not limited to a specific number of leading zeros or a specific character set in the beginning. The downside with this solution is that it has to be [alphabetical][numerical].
private static string Increase(string productNo)
{
// This is a regex to split it into to groups.
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*[ _]?)(?<Numeric>[0-9]*)");
// Match the input string for the regex.
var match = numAlpha.Match(productNo);
// Get the alphabetical part.
var alpha = match.Groups["Alpha"].Value;
// Get the numeric part.
int num = int.Parse(match.Groups["Numeric"].Value);
// Add +1
num++;
// Combine the alphabetical part with the increased number, but use PadLeft to maintain the padding (leading zeros).
var newString = string.Format("{0}{1}", alpha, num.ToString().PadLeft(match.Groups["Numeric"].Value.Length, '0'));
return newString;
}
Console.WriteLine(Increase("DTS00008"));
Console.WriteLine(Increase("DTS00010"));
Console.WriteLine(Increase("DTS00020"));
Console.WriteLine(Increase("DTS00099"));
Console.WriteLine(Increase("PRODUCT0000009"));
Console.WriteLine(Increase("PRODUCT0000001"));
Output:
DTS00009
DTS00011
DTS00021
DTS00100
PRODUCT0000010
PRODUCT0000002

Related

Get exponential value using regular expression

I have string like this:
strings s = "1.0E-20"
Is there a way to get only -20 from this using regex?
I tried this:
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE][-+]?[0-9]+)?
this gets me e-20 in group5 but still not just -20.
Use Regex for dealing with text, use Math(s) for dealing with numbers:
Math.Log10(Convert.ToDouble("1.0E-20")) // returns -20
To make sure your string input is a valid double use TryParse:
double d, result = 0.0;
if (Double.TryParse("1.0E-20", out d))
{
result = Math.Log10(d);
}
else
{
// handle error
}
Also, if you want to get the 1.0 (multiplier) from your input:
var d = Convert.ToDouble("1.0E-20");
var exponent = Math.Log10(d);
var multiplier = d / exponent;
No need for Regex when string methods can do wonders
string str = "1.0E-20";
str = str.Substring(str.IndexOf('E') + 1);
You can do that without Regex like:
string s = "1.0E-20";
string newStr = s.Substring(s.IndexOf('E') + 1);
Later you can parse the string to number like:
int number;
if (!int.TryParse(newStr, out number))
{
//invalid number
}
Console.WriteLine(number);
You can also use string.Split like:
string numberString = s.Split('E')[1]; //gives "-20"
Its better if you add check for string/array length when access string.Substring or accessing element 1 after split.
var x = str.IndexOf("E") != -1 ? str.Substring(str.IndexOf("E") + 1) : "1";
If you want to use regular expressions to achieve this, you should switch up your capture groups.
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE])([-+]?[0-9]+)?
Group 6 will contain -20 with your given example with the regular expression above. Note how the parentheses have moved. We might need more information from you though. Do you have any more sample data? What's the end goal here?

Parse string and return only the information between bracket symbols. C# Winforms

I would like to parse a string to return only a value that is in between bracket symbols, such as [10.2%]. Then I would need to strip the "%" symbol and convert the decimal to a rounded up/down integer. So, [10.2%] would end up being 10. And, [11.8%] would end up being 12.
Hopefully I have provided sufficient information.
Math.Round(
double.Parse(
"[11.8%]".Split(new [] {"[", "]", "%"},
StringSplitOptions.RemoveEmptyEntries)[0]))
Why not use Regex?
In this example, I am assuming that your value inside the brackets always are a double with decimals.
string WithBrackets = "[11.8%]";
string AsDouble = Regex.Match(WithBrackets, "\d{1,9}\.\d{1,9}").value;
int Out = Math.Round(Convert.ToDouble(AsDouble.replace(".", ","));
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
If you can ensure that the content between the brackets is of the form <decimal>%, then this little function will return the value between the fist set of brackets. If there are more than one values you need to extract then you will need to modify it somewhat.
public decimal getProp(string str)
{
int obIndex = str.IndexOf("["); // get the index of the open bracket
int cbIndex = str.IndexOf("]"); // get the index of the close bracket
decimal d = decimal.Parse(str.Substring(obIndex + 1, cbIndex - obIndex - 2)); // this extracts the numerical part and converts it to a decimal (assumes a % before the ])
return Math.Round(d); // return the number rounded to the nearest integer
}
For example getProp("I like cookies [66.7%]") gives the Decimal number 67
Use regular expressions (Regex) to find the required words within one bracket.
This is the code you need:
Use an foreach loop to remove the % and convert to int.
List<int> myValues = new List<int>();
foreach(string s in Regex.Match(MYTEXT, #"\[(?<tag>[^\]]*)\]")){
s = s.TrimEnd('%');
myValues.Add(Math.Round(Convert.ToDouble(s)));
}

Parse without string split

This is a spin-off from the discussion in some other question.
Suppose I've got to parse a huge number of very long strings. Each string contains a sequence of doubles (in text representation, of course) separated by whitespace. I need to parse the doubles into a List<double>.
The standard parsing technique (using string.Split + double.TryParse) seems to be quite slow: for each of the numbers we need to allocate a string.
I tried to make it old C-like way: compute the indices of the beginning and the end of substrings containing the numbers, and parse it "in place", without creating additional string. (See http://ideone.com/Op6h0, below shown the relevant part.)
int startIdx, endIdx = 0;
while(true)
{
startIdx = endIdx;
// no find_first_not_of in C#
while (startIdx < s.Length && s[startIdx] == ' ') startIdx++;
if (startIdx == s.Length) break;
endIdx = s.IndexOf(' ', startIdx);
if (endIdx == -1) endIdx = s.Length;
// how to extract a double here?
}
There is an overload of string.IndexOf, searching only within a given substring, but I failed to find a method for parsing a double from substring, without actually extracting that substring first.
Does anyone have an idea?
There is no managed API to parse a double from a substring. My guess is that allocating the string will be insignificant compared to all the floating point operations in double.Parse.
Anyway, you can save the allocation by creating a "buffer" string once of length 100 consisting of whitespace only. Then, for every string you want to parse, you copy the chars into this buffer string using unsafe code. You fill the buffer string with whitespace. And for parsing you can use NumberStyles.AllowTrailingWhite which will cause trailing whitespace to be ignored.
Getting a pointer to string is actually a fully supported operation:
string l_pos = new string(' ', 100); //don't write to a shared string!
unsafe
{
fixed (char* l_pSrc = l_pos)
{
// do some work
}
}
C# has special syntax to bind a string to a char*.
if you want to do it really fast, i would use a state machine
this could look like:
enum State
{
Separator, Sign, Mantisse etc.
}
State CurrentState = State.Separator;
int Prefix, Exponent, Mantisse;
foreach(var ch in InputString)
{
switch(CurrentState)
{ // set new currentstate in dependence of ch and CurrentState
case Separator:
GotNewDouble(Prefix, Exponent, Mantisse);
}
}

Is there an easy way to trim the last three characters off a string

I have strings like this:
var a = "abcdefg";
var b = "xxxxxxxx";
The strings are always longer than five characters.
Now I need to trim off the last 3 characters. Is there some simple way that I can do this with C#?
In the trivial case you can just use
result = s.Substring(0, s.Length-3);
to remove the last three characters from the string.
Or as Jason suggested Remove is an alternative:
result = s.Remove(s.Length-3)
Unfortunately for unicode strings there can be a few problems:
A unicode codepoint can consist of multiple chars since the encoding of string is UTF-16 (See Surrogate pairs). This happens only for characters outside the basic plane, i.e. which have a code-point >2^16. This is relevant if you want to support Chinese.
A glyph (graphical symbol) can consist of multiple codepoints. For example ä can be written as a followed by a combining ¨.
Behavior with right-to-left writing might not be what you want either
You want String.Remove(Int32)
Deletes all the characters from this string beginning at a specified
position and continuing through the last position.
If you want to perform validation, along the lines of druttka's answer, I would suggest creating an extension method
public static class MyStringExtensions
{
public static string SafeRemove(this string s, int numCharactersToRemove)
{
if (numCharactersToRemove > s.Length)
{
throw new ArgumentException("numCharactersToRemove");
}
// other validation here
return s.Remove(s.Length - numCharactersToRemove);
}
}
var s = "123456";
var r = s.SafeRemove(3); //r = "123"
var t = s.SafeRemove(7); //throws ArgumentException
string a = "abcdefg";
a = a.Remove(a.Length - 3);
string newString = oldString.Substring(0, oldString.Length - 4);
If you really only need to trim off the last 3 characters, you can do this
string a = "abcdefg";
if (a.Length > 3)
{
a = a.Substring(0, a.Length-3);
}
else
{
a = String.Empty;
}

How can I parse an integer and the remaining string from my string?

I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"

Categories