split and increase in asp .net - c#

I have productID="ab1002" which is in string format.
productID is not always start with ab it might be xy,ptz.So i want to split the numeric part of ID and increase by 1.
means
string productID="ab1002";
want a result
string newProductID="ab1003";
How to get this.thanks for help.

To remove the characters:
string sNumbers = Regex.Replace(productID,"[^A-Z][a-z]",String.Empty); // To remove letters
string sText = Regex.Replace(productID,"[^0-9]",String.Empty); // To remove numbers
string iTmp = int.Parse(sNumbers); // Convert to integer
iTmp++;
string newProductID = sText + iTmp.ToString();

Would you please try with below code, this works fine according to you, thanks for your time
productID = (Regex.Replace(productID, "[0-9]", String.Empty)) +
(Convert.ToInt32(Regex.Replace(productID, "[a-z]", string.Empty, RegexOptions.IgnoreCase)) + 1).ToString();

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.

Convert string value to decimal with thousand separator?

This might be a very simple question.
Suppose text box show value 10,000.12 when user edits data by mistake he remove first two numbers like ,000.12 and using this textbox in the calculation then it gives an exception. I want a just validate text box.
For Example:
string str = ",100.12;"
Convert to
decimal number = 100.12;
Any Idea?.
It shows only whole number when user remove any thousand separator.
This is pretty messed up and I am not sure if all of you strings will look the same, but in case they do this might do the trick:
string str = ",0,100.12";
decimal number;
bool converted = decimal.TryParse(str.Substring(str.LastIndexOf(",") + 1), out number);
The variable converted will tell you whether or not your string was converted and you will not an exception.
Good luck!
If I understood the question, you want to remove all characters that would prevent the parse routine from failing.
string str = ",0,100.12";
var modified = new StringBuilder();
foreach (char c in str)
{
if (Char.IsDigit(c) || c == '.')
modified.Append(c);
}
decimal number= decimal.Parse(modified.ToString());
string a = "100.12";
decimal b = Convert.ToDecimal(a);
string str = ",0,100.12;";
var newstr = Regex.Replace(str,#"[^\d\.]+","");
decimal d = decimal.Parse(newstr, CultureInfo.InvariantCulture);

String Find & Replace Method

I need to locate a specific part of a string value like the one below, I need to alter the "Meeting ID" to a specific number.
This number comes from a dropdownlist of multiple numbers, so I cant simply use find & replace. As the text could change to one of multiple numbers before the user is happy.
The "0783," part of the string never changes, and "Meeting ID" is always followed by a ",".
So i need to get to "0783, INSERT TEXT ," and then insert the new number on the Index Changed event.
Here is an example :-
Business Invitation, start time, M Problem, 518-06-xxx, 9999 999
0783, Meeting ID, xxx ??
What is the best way of locating this string and replacing the test each time?
I hope this makes sense guys?
Okay, so there are several ways of doing this, however this seems to be a string you have control over so I'm going to say here's what you want to do.
var myString = string.Format("Business Invitation, start time, M Problem, 518-06-xxx, 9999 999 0783, {0}, xxx ??", yourMeetingId);
If you don't have control over it then you're going to have to be a bit more clever:
var startingIndex = myString.IndexOf("0783, ");
var endingIndex = myString.IndexOf(",", startingIndex + 6);
var pattern = myString.Substring(startingIndex + 6, endingIndex - (startingIndex + 6));
myString = myString.Replace(pattern, yourMeetingId);
You should store your "current" Meeting ID in a variable, changing it along with your user's actions, and then use that same global variable whenever you need the string.
This way, you don't have to worry about what's inside the string and don't need to mess with array indexes. You will also be safe from magic numbers / strings, which are bound to blow up in your face at some point in the future.
You can try with Regex.Replace method
string pattern = #"\d{3},";
Regex regex = new Regex(pattern);
var inputStr = "518-06-xxx, 9999 999 0783";
var replace = "..."
var outputStr = regex.Replace(inputStr, replace);
use Regex.Split by token "0783," then in the second string in the array return split by token "," the first element in the string array would be where you would insert new text. Then use string.Join to join the first split with "0783," and the join the second with ",".
string temp = "Business Invitation, start time, M Problem, 518-06-xxx, 9999 999 0783, Meeting ID, xxx ??";
string newID = "1234";
string[] firstSplits = Regex.Split(temp, "0783,");
string[] secondSplits = Regex.Split(firstSplits[1], ",");
secondSplits[0] = newID;
string #join = string.Join(",", secondSplits);
firstSplits[1] = #join;
string newString = string.Join("0783,", firstSplits);

C# , Substring How to access last elements of an array/string using substring

I am generating 35 strings which have the names ar15220110910, khwm20110910 and so on.
The string contains the name of the Id (ar152,KHWM), and the date (20110910). I want to extract the Id, date from the string and store it in a textfile called StatSummary.
My code statement is something like this
for( int 1= 0;i< filestoextract.count;1++)
{
// The filestoextract contains 35 strings
string extractname = filestoextract(i).ToString();
statSummary.writeline( extractname.substring(0,5) + "" +
extractname.substring(5,4) + "" + extractname.substring(9,2) + "" +
extractname.substring(11,2));
}
When the station has Id containing 5 letters, then this code executes correctly but when the station Id is KHWM or any other 4 letter name then the insertion is all messed up. I am running this inside a loop. So I have tried keeping the code as dynamic as possible. Could anyone help me to find a way without hardcoding it. For instance accessing the last 8 elements to get the date??? I have searched but am not able to find a way to do that.
For the last 8 digits, it's just:
extractname.Substring(extractname.Length-8)
oh, I'm sorry, and so for your code could be:
int l = extractname.Length;
statSummary.WriteLine(extractname.substring(0,l-8) + "" +
extractname.Substring(l-8,4) + "" + extractname.Substring(l-4,2) + "" +
extractname.Substring(l-2,2));
As your ID length isn't consistent, it would probably be a better option to extract the date (which is always going to be 8 chars) and then treat the remainder as your ID e.g.
UPDATED - more robust by actually calculating the length of the date based on the format. Also validates against the format to make sure you have parsed the data correctly.
var dateFormat = "yyyyMMdd"; // this could be pulled from app.config or some other config source
foreach (var file in filestoextract)
{
var dateStr = file.Substring(file.Length-dateFormat.Length);
if (ValidateDate(dateStr, dateFormat))
{
var id = file.Substring(0, file.Length - (dateFormat.Length+1));
// do something with data
}
else
{
// handle invalid filename
}
}
public bool ValidateDate(stirng date, string date_format)
{
try
{
DateTime.ParseExact(date, date_format, DateTimeFormatInfo.InvariantInfo);
}
catch
{
return false;
}
return true;
}
You could use a Regex :
match = Regex.Match ("khwm20110910","(?<code>.*)(?<date>.{6})" );
Console.WriteLine (match.Groups["code"] );
Console.WriteLine (match.Groups["date"] );
To explain the regex pattern (?<code>.*)(?<date>.{6}) the brackets groups creates a group for each pattern. ?<code> names the group so you can reference it easily.
The date group takes the last six characters of the string. . says take any character and {6} says do that six times.
The code group takes all the remaining characters. * says take as many characters as possible.
for each(string part in stringList)
{
int length = part.Length;
int start = length - 8;
string dateString = part.Substring(start, 8);
}
That should solve the variable length to get the date. The rest of the pull is most likely dependent on a pattern (suggested) or the length of string (when x then the call is 4 in length, etc)
If you ID isn't always the same amount of letters you should seperate the ID and the Date using ',' or somthing then you use this:
for( int 1= 0;i< filestoextract.count;1++)
{
string extractname = filestoextract[i].ToString();
string ID = extractname.substring(0, extractname.IndexOf(','));
string Date = extractname.substring(extractname.IndexOf(','));
Console.WriteLine(ID + Date);
}

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