Application running in ASP.NET is not giving the desired output - c#

I have an application not calculating the percentage correctly. It is suppose to calculate the input in percent. But there is bug somewhere which is preventing it from doing so.
For example, if I input any number starting with decimals like 0.01 or 0.001 or 0.02 etc it will give me the output 1, 0.1 and 2 respectively. If I punch in any whole numbers like 1, 2, 3, 10, etc, it will always give the same output i.e 0.01.
This application was done by some contractors 5 years ago. The main in-charge of this application has left. Which leaves me and my little experience in c# and asp.net in figuring out the issue. Before I seek any further help, I thought I should ask geniuses out there and see what they have to say, may be I will end up figuring out the issue with your help. I did talk to other IT people in my department, they guess it might be because of the code below.
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
I am not 100% sure how to debug or find the issue. If anyone can point me out anything that might help or provide me some resources that I can look it up, it will be really helpful. I have copied few of the lines of code. I can provide more information but don't know which one will be more relevant.
protected string MinUp
{
get
{
return (string)ViewState["minup"];
}
set
{
ViewState["minup"] = value;
}
}
==============
MinUp = rows["process_minimum_up"].ToString();
PIMSSource = rows["pims_source"].ToString();
//MinUp = Convert.ToDouble()
if (MinUp != string.Empty || MinUp.Length > 0)
{
MinUp = Convert.ToString(Convert.ToDouble(MinUp) * 100);
}
=====================
if (DCFoption != "P")
{
MinUp = "";
}
if (DcfmSeq != "0")
{
int caret;
caret = ddlvbcfmseq.SelectedValue.IndexOf("^");
DcfmSeq = DcfmSeq.Substring(0, caret);
}
if (DCFoption != "P" && ddlpdwnlst.SelectedItem.Value == "0")
{
MinUp = "";
}
if (PIMSTagId == "Not specified")
{
PIMSTagId = "";
}
if (MinUp != string.Empty || MinUp.Length > 0)
{
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
{
MinUp = Convert.ToString(Convert.ToInt32(MinUp) / 100);
if (Convert.ToInt32(MinUp) < 0)
{
MinUp = "0";
}
else if (Convert.ToInt32(MinUp) > 1)
{
MinUp = "1";
}
}
}
if ((DCFoption == string.Empty || DCFoption.Length < 1) || DCFoption == "D")
{
MinUp = "";
}
if (MinUp != string.Empty || MinUp.Length > 0)
{
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
{
if (Convert.ToDouble(MinUp) <= 0)
{
MinUp = ".0001";
}
}
}
=======================
if (rdbProcess.Checked == true && (txtminup.Text == string.Empty || txtminup.Text.Length < 1) && ddlpdwnlst.SelectedItem.Value == "0")
{
Utilities.ShowAlert(this.Page, Resources.Resource.RIPimsUpload_MinUptime.ToString());
txtminup.Focus();
======================
int n;
if (!int.TryParse(string.IsNullOrEmpty(txtRound.Text) ? "0" : txtRound.Text, out n))
{
Utilities.ShowAlert(this.Page, Resources.Resource.RIPimsUpload_RoundingNum.ToString());
}
else if (!IsDouble(txtminup.Text))
======================
try
{
DBResults objDBResult = new DBResults();
WEIS.RIPimsUpload objRI = new WEIS.RIPimsUpload();
objDBResult = objRI.SaveItemInsert(reciseq, shortname, name, eiscprocess2, period, media, euseq, eqmtseq, eiscuom, pollseq, dcfmseq, rounding, formula, physmin, physmax, warn1min, warn1max, warn2min, warn2max, pimsStatus, pimsTagidp, datapoint, freq, periodoffset, initpimstTagId, initDataPoint, initLoadFrequency, initperiodoffset, day0result, retention, audituser, dcfoption, minup, pimssource);
if (objDBResult.oraErrMsg.Trim().ToString().Length > 1)
{
Exception ex = new Exception(objDBResult.oraErrMsg.ToString());
throw ex;
}
return objDBResult.oraIntReturn;
}
===============================
protected int SaveItemUpdate(int reciseq, string shortname, string name, int eiscprocess2, int period, int media, int euseq, int eqmtseq, int eiscuom, int pollseq, int dcfmseq, string rounding, string formula, string physmin, string physmax, string warn1min, string warn1max, string warn2min, string warn2max, string pimsStatus, string pimsTagidp, string datapoint, string freq, char periodoffset, string initpimstTagId, char initDataPoint, char initLoadFrequency, char initperiodoffset, string day0result, string retention, string audituser, string dcfoption, string minup, string pimssource)
{
try
{
DBResults objDBResult = new DBResults();
WEIS.RIPimsUpload objRI = new WEIS.RIPimsUpload();
objDBResult = objRI.SaveItemUpdate(reciseq, shortname, name, eiscprocess2, period, media, euseq, eqmtseq, eiscuom, pollseq, dcfmseq, rounding, formula, physmin, physmax, warn1min, warn1max, warn2min, warn2max, pimsStatus, pimsTagidp, datapoint, freq, periodoffset, initpimstTagId, initDataPoint, initLoadFrequency, initperiodoffset, day0result, retention, audituser, dcfoption, minup, pimssource);
if (objDBResult.oraErrMsg.Trim().ToString().Length > 1)
{
Exception ex = new Exception(objDBResult.oraErrMsg.ToString());
throw ex;
}
=============================
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
lblUserMsgText.Text = "";
bool dcfm = ddlvbcfmseq.Enabled;
string minup, dcfoption="";
minup = txtminup.Text;
if (rdbNone.Checked == true)
{
dcfoption = "NONE";
}
else if (rdbProcess.Checked == true)
{
dcfoption = "P";
}
else if (rdbData.Checked == true)
{
dcfoption = "D";
}
Index = Convert.ToInt32(rdbListradios.SelectedIndex);
SaveItem();
RetainClientControlValues(dcfm, dcfoption, minup);
}
==============================
protected void btnExcMod_Click(object sender, EventArgs e)
{
try
{
lblUserMsgText.Text = "";
bool dcfm = ddlvbcfmseq.Enabled;
string minup, dcfoption = "";
Index = Convert.ToInt32(rdbListradios.SelectedIndex);
minup = txtminup.Text;
if (rdbNone.Checked == true)
{
dcfoption = "NONE";
}
else if (rdbProcess.Checked == true)
{
dcfoption = "P";
}
else if (rdbData.Checked == true)
{
dcfoption = "D";
}
Button btn = (Button)sender;
int evntseq = Convert.ToInt32(btn.CommandArgument.ToString());
RetainClientControlValues(dcfm, dcfoption, minup);
//Response.Write("you clicked on button");
}

#Umamaheswaran thanks for the hint.
int n;
if (int.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
Above was the initial code and i changed it to
double n;
if (double.TryParse(string.IsNullOrEmpty(txtminup.Text) ? "0" : txtminup.Text, out n))
and also whereever it was converting to
Convert.ToInt32
I changed it to
Convert.ToDouble
I don't know whatever was the issue as I am not very much familiar with asp.net and c# but changing above code solved the issue. Now whenever I input a number it will change to percentage and save it to correct format.
Thank you all for your help and concern. I have few more different issues. I will try to solve it if not I will post it here and try to be concise and to the point.

Related

Value was either too large or too small for an Int32 in Textbox

I am getting error on this int b = Convert.ToInt32(qty.Text); if i type more than 11 numbers in quantity textbox
if (Item_Name.Text == dr["Item_Name"].ToString() && Item_Code.Text == dr["Item_Code"].ToString())
{
int a = Convert.ToInt32(dr["Selling_Price"].ToString());
if (qty.Text == "")
{
Selling_Price.Text = "";
}
else
{
int b = Convert.ToInt32(qty.Text); //Error On This Line
int c = a * b;
Selling_Price.Text = c.ToString();
}
}
You're getting that exception because an integer cannot store a number that large.
Int32.MaxValue Field : The value of this constant is 2147483647
Switching to a long should solve the problem for you. When you're dealing with numbers that represent money, you might want to consider using decimal too.
if (Item_Name.Text == dr["Item_Name"].ToString() && Item_Code.Text == dr["Item_Code"].ToString())
{
int price = Convert.ToInt32(dr["Selling_Price"].ToString());
if (qty.Text == "")
{
Selling_Price.Text = "";
}
else
{
long quantity = Convert.ToInt64(qty.Text);
long total = price * quantity;
Selling_Price.Text = total.ToString();
}
}

Why looping twice on string length test

I'm working in C# (2013) Windows Forms. My instructor wanted us to ensure that the txtStateInput is upperCase when we hit the calculate button. However when I input a two character string such as "wi" and then hit calculate, it throws the message "enter valid state" and clears out the textbox. When I enter the "wi" in a second time then it works. I can't figure out why this is happening, the code would lead me to believe that it would check to ensure the string in txtStateInput is two characters and then when calculate is clicked it would uppercase the string. I can't figure out why it only works once I enter in the state "wi" a second time.
private void btnCalc_Click(object sender, EventArgs e)
{
//declare variables.
int startPop = 0;
int endPop = 0;
string Message = "Error";
decimal Percent = 0.0m;
string State = "";
string City = String.Empty;
int dTimes = 0;
try
{
City = txtCityInput.Text;
//System Globalization was initialized so this method works.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
txtCityInput.Text = myTI.ToTitleCase(City);
if(txtStateInput.Text.Length != 2)
{
MessageBox.Show("Enter valid State");
txtStateInput.Focus();
txtStateInput.SelectAll();
}
else
{
State = txtStateInput.Text.ToUpper();
txtStateInput.Text = State;
if ((int.TryParse(txtStartPopInput.Text, out startPop)) && int.TryParse(txtEndPopInput.Text, out endPop))
{
if ((startPop > 0) && (endPop > 0))
{
//if population has decreased.
if ((startPop > endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Decrease of " + Percent.ToString("p");
}
//if population has increased.
if ((startPop < endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "Pop. Increase of " + Percent.ToString("p");
}
//if population has not changed.
if ((startPop == endPop))
{
Percent = ((decimal.Parse(endPop.ToString()) - decimal.Parse(startPop.ToString())) / decimal.Parse(startPop.ToString()));
Message = "No Change in Population";
}
}
else
{
MessageBox.Show("Please enter valid population figures.");
}
}
if (int.TryParse(txtDisplayTimes.Text, out dTimes))
{
if (dTimes > 0)
{
lstResults.Items.Clear();
int iSum = 0;
int iLoopCount = dTimes;
//displays the results according to value in txtDisplayTimes.
for (iSum = 1; iSum <= iLoopCount; iSum++)
{
lstResults.Items.Add(Message);
}
}
}
}
}
catch
{
MessageBox.Show("Something went wrong.");
}
}

TextBox Indexof and LastIndexOf

Because TextBox doesn't have a find function, I've created and modified my own version of it to my needs. I've created to functions. One for Search Next and another for Search Previous
My problem is that:
If my search term is more than 1 character long and I've searched
for the term four times, IF on the 4th term I decide the click on
search previous it goes back to the previous search term and that
works fine. Now because I clicked on search previous 4 times and I
went to the 3rd search term using previous, IF I decide to go the
4th term again using Find Next, I have to double click on find next
and then it selects the 4th term.
If my search term is 1 character long and I want to search for a
character, I type the character e.g. 'o' and it goes through each
character in the textbox but once I decide to go back using search
previous, I have to double click search previous button and then it
goes back and if I decide to search next I have to double click
again then it searches next.
This might help understand the double click and single click:
http://media.giphy.com/media/3xz2BJgF2DrtcCnP1e/giphy.gif
I've been trying to get this to work for quite a while now and I've had no luck. I have no idea where I'm going with this and before I confuse myself it will be great if someone can help me with this.
My code for:
Variables
public int startPostion = 0;
boolean passedNext;
public int pos = 0;
Search Next
public bool FindAndSelectNext(string TextToFind, bool MatchCase)
{
try
{
var mode = MatchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
int position = TheTextBox.Text.IndexOf(TextToFind, startPostion, mode);
pos = position;
if (position == -1)
{
var TheString = TheTextBox.Text;
var foundposition2 = TheString.IndexOf(TextToFind, mode);
TheTextBox.SelectionStart = foundposition2;
TheTextBox.SelectionLength = TextToFind.Length;
startPostion = foundposition2 + TextToFind.Length;
TheTextBox.Focus();
passedNext = false;
Debug.WriteLine("1");
return true;
}
else
{
TheTextBox.SelectionStart = position;
TheTextBox.SelectionLength = TextToFind.Length;
startPostion = position + TextToFind.Length;
TheTextBox.Focus();
passedNext = true;
Debug.WriteLine("2");
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Could not find '{0}' in the document.", TextToFind), ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return true;
}
Search Previous
public bool FindAndSelectPrevious(string TextToFind, bool MatchCase)
{
StringComparison mode = MatchCase ? StringComparison.CurrentCulture : StringComparison.CurrentCultureIgnoreCase;
if (passedNext == true)
{
int foundPosition = startPostion < 0 ? TheTextBox.Text.Length : startPostion - 1;
foundPosition = TheTextBox.Text.LastIndexOf(TextToFind, pos, mode);
passedNext = false;
if (foundPosition < 0)
{
if (startPostion < 0)
{
MessageBox.Show(string.Format("Could not find '{0}' in the document.", TextToFind), ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
foundPosition = TheTextBox.Text.LastIndexOf(TextToFind, mode);
Debug.WriteLine("1p");
}
TheTextBox.SelectionStart = foundPosition;
TheTextBox.SelectionLength = TextToFind.Length;
startPostion = foundPosition;
TheTextBox.Focus();
Debug.WriteLine("2p");
passedNext = false;
}
else
{
int foundPosition = startPostion < 0 ? TheTextBox.Text.Length : startPostion;
foundPosition = TheTextBox.Text.LastIndexOf(TextToFind, foundPosition, mode);
if (foundPosition < 0)
{
if (startPostion < 0)
{
MessageBox.Show(string.Format("Could not find '{0}' in the document.", TextToFind), ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
return false;
}
foundPosition = TheTextBox.Text.LastIndexOf(TextToFind, mode);
}
if (!(foundPosition == -1))
{
try
{
int foundPositionz = startPostion < 0 ? TheTextBox.Text.Length : startPostion - 1;
foundPositionz = TheTextBox.Text.LastIndexOf(TextToFind, foundPositionz, mode);
TheTextBox.SelectionStart = foundPositionz;
TheTextBox.SelectionLength = TextToFind.Length;
startPostion = foundPositionz;
TheTextBox.Focus();
}
catch (Exception ex)
{
var TheString = TheTextBox.Text;
var foundposition2 = TheString.LastIndexOf(TextToFind, mode);
TheTextBox.SelectionStart = foundposition2;
TheTextBox.SelectionLength = TextToFind.Length;
startPostion = foundposition2;
TheTextBox.Focus();
Debug.WriteLine("12p");
}
}
else
{
MessageBox.Show(string.Format("Could not find '{0}' in the document.", TextToFind), ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
return true;
}
IMHO, you should just find all the matches the first time the user tries to find something, and then keep an index indicating which match is to be selected/highlighted.
For example:
private List<int> _matches;
private string _textToFind;
private bool _matchCase;
private int _matchIndex;
private void MoveToNextMatch(string textToFind, bool matchCase, bool forward)
{
if (_matches == null ||
_textToFind != textToFind ||
_matchCase != matchCase)
{
int startIndex = 0, matchIndex;
StringComparison mode = matchCase ?
StringComparison.CurrentCulture :
StringComparison.CurrentCultureIgnoreCase;
_matches = new List();
while (startIndex < TheTextBox.Text.Length &&
(matchIndex = TheTextBox.Text.IndexOf(textToFind, startIndex, mode)) >= 0)
{
_matches.Add(matchIndex);
startIndex = matchIndex + textToFind.Length;
}
_textToFind = textToFind;
_matchCase = matchCase;
_matchIndex = forward ? 0 : _matches.Count - 1;
}
else
{
_matchIndex += forward ? 1 : -1;
if (_matchIndex < 0)
{
_matchIndex = _matches.Count - 1;
}
else if (_matchIndex >= _matches.Count)
{
_matchIndex = 0;
}
}
if (_matches.Count > 0)
{
TheTextBox.SelectionStart = _matches[_matchIndex];
TheTextBox.SelectionLength = textToFind.Length;
TheTextBox.Focus();
}
else
{
MessageBox.Show(string.Format(
"Could not find '{0}' in the document.", TextToFind),
ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
public bool FindAndSelectNext(string textToFind, bool matchCase)
{
MoveToNextMatch(textToFind, matchCase, true);
}
public bool FindAndSelectPrevious(string textToFind, bool matchCase)
{
MoveToNextMatch(textToFind, matchCase, false);
}

RichTextBox is finding my search terms in funny places

I'm trying to find instances of a string in a WPF RichTextBox. What I have now almost works, but it highlights the wrong section of the document.
private int curSearchLocation;
private void FindNext_Click(object sender, RoutedEventArgs e)
{
TextRange text = new TextRange(RichEditor.Document.ContentStart, RichEditor.Document.ContentEnd);
var location = text.Text.IndexOf(SearchBox.Text, curSearchLocation, StringComparison.CurrentCultureIgnoreCase);
if (location < 0)
{
location = text.Text.IndexOf(SearchBox.Text, StringComparison.CurrentCultureIgnoreCase);
}
if (location >= 0)
{
curSearchLocation = location + 1;
RichEditor.Selection.Select(text.Start.GetPositionAtOffset(location), text.Start.GetPositionAtOffset(location + SearchBox.Text.Length));
}
else
{
curSearchLocation = 0;
MessageBox.Show("Not found");
}
RichEditor.Focus();
}
This is what happens when I search for "document":
This is because GetPositionAtOffset includes non-text elements such as opening and closing tags in its offset, which is not what I want. I couldn't find a way to ignore these elements, and I also couldn't find a way to directly get a TextPointer to the text I want, which would also solve the problem.
How can I get it to highlight the correct text?
Unfortunately the TextRange.Text strips out non-text characters, so in this case the offset computed by IndexOf will be slightly too low. That is the main problem.
I tried to solve your problem and found working solution that works fine even when we have formatted text in many paragraphs.
A lot of help is taken from this CodeProject Article. So also read that article.
int curSearchLocation;
private void FindNext_Click(object sender, RoutedEventArgs e)
{
TextRange text = new TextRange(RichEditor.Document.ContentStart, RichEditor.Document.ContentEnd);
var location = text.Text.IndexOf(SearchBox.Text, curSearchLocation, StringComparison.CurrentCultureIgnoreCase);
if (location < 0)
{
location = text.Text.IndexOf(SearchBox.Text, StringComparison.CurrentCultureIgnoreCase);
}
if (location >= 0)
{
curSearchLocation = location + 1;
Select(location, SearchBox.Text.Length);
}
else
{
curSearchLocation = 0;
MessageBox.Show("Not found");
}
RichEditor.Focus();
}
public void Select(int start, int length)
{
TextPointer tp = RichEditor.Document.ContentStart;
TextPointer tpLeft = GetPositionAtOffset(tp, start, LogicalDirection.Forward);
TextPointer tpRight = GetPositionAtOffset(tp, start + length, LogicalDirection.Forward);
RichEditor.Selection.Select(tpLeft, tpRight);
}
private TextPointer GetPositionAtOffset(TextPointer startingPoint, int offset, LogicalDirection direction)
{
TextPointer binarySearchPoint1 = null;
TextPointer binarySearchPoint2 = null;
// setup arguments appropriately
if (direction == LogicalDirection.Forward)
{
binarySearchPoint2 = this.RichEditor.Document.ContentEnd;
if (offset < 0)
{
offset = Math.Abs(offset);
}
}
if (direction == LogicalDirection.Backward)
{
binarySearchPoint2 = this.RichEditor.Document.ContentStart;
if (offset > 0)
{
offset = -offset;
}
}
// setup for binary search
bool isFound = false;
TextPointer resultTextPointer = null;
int offset2 = Math.Abs(GetOffsetInTextLength(startingPoint, binarySearchPoint2));
int halfOffset = direction == LogicalDirection.Backward ? -(offset2 / 2) : offset2 / 2;
binarySearchPoint1 = startingPoint.GetPositionAtOffset(halfOffset, direction);
int offset1 = Math.Abs(GetOffsetInTextLength(startingPoint, binarySearchPoint1));
// binary search loop
while (isFound == false)
{
if (Math.Abs(offset1) == Math.Abs(offset))
{
isFound = true;
resultTextPointer = binarySearchPoint1;
}
else
if (Math.Abs(offset2) == Math.Abs(offset))
{
isFound = true;
resultTextPointer = binarySearchPoint2;
}
else
{
if (Math.Abs(offset) < Math.Abs(offset1))
{
// this is simple case when we search in the 1st half
binarySearchPoint2 = binarySearchPoint1;
offset2 = offset1;
halfOffset = direction == LogicalDirection.Backward ? -(offset2 / 2) : offset2 / 2;
binarySearchPoint1 = startingPoint.GetPositionAtOffset(halfOffset, direction);
offset1 = Math.Abs(GetOffsetInTextLength(startingPoint, binarySearchPoint1));
}
else
{
// this is more complex case when we search in the 2nd half
int rtfOffset1 = startingPoint.GetOffsetToPosition(binarySearchPoint1);
int rtfOffset2 = startingPoint.GetOffsetToPosition(binarySearchPoint2);
int rtfOffsetMiddle = (Math.Abs(rtfOffset1) + Math.Abs(rtfOffset2)) / 2;
if (direction == LogicalDirection.Backward)
{
rtfOffsetMiddle = -rtfOffsetMiddle;
}
TextPointer binarySearchPointMiddle = startingPoint.GetPositionAtOffset(rtfOffsetMiddle, direction);
int offsetMiddle = GetOffsetInTextLength(startingPoint, binarySearchPointMiddle);
// two cases possible
if (Math.Abs(offset) < Math.Abs(offsetMiddle))
{
// 3rd quarter of search domain
binarySearchPoint2 = binarySearchPointMiddle;
offset2 = offsetMiddle;
}
else
{
// 4th quarter of the search domain
binarySearchPoint1 = binarySearchPointMiddle;
offset1 = offsetMiddle;
}
}
}
}
return resultTextPointer;
}
int GetOffsetInTextLength(TextPointer pointer1, TextPointer pointer2)
{
if (pointer1 == null || pointer2 == null)
return 0;
TextRange tr = new TextRange(pointer1, pointer2);
return tr.Text.Length;
}
Hope so this code will work for your case.

How to separate character and number part from string

E.g., I would like to separate:
OS234 to OS and 234
AA4230 to AA and 4230
I have used following trivial solution, but I am quite sure that there should be a more efficient and robust solution .
private void demo()
{ string cell="ABCD4321";
int a = getIndexofNumber(cell);
string Numberpart = cell.Substring(a, cell.Length - a);
row = Convert.ToInt32(rowpart);
string Stringpart = cell.Substring(0, a);
}
private int getIndexofNumber(string cell)
{
int a = -1, indexofNum = 10000;
a = cell.IndexOf("0"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("1"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("2"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("3"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("4"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("5"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("6"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("7"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("8"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("9"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
if (indexofNum != 10000)
{ return indexofNum; }
else
{ return 0; }
}
Regular Expressions are best suited for this kind of work:
using System.Text.RegularExpressions;
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(input);
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;
Use Linq to do this
string str = "OS234";
var digits = from c in str
select c
where Char.IsDigit(c);
var alphas = from c in str
select c
where !Char.IsDigit(c);
Everyone and their mother will give you a solution using regex, so here's one that is not:
// s is string of form ([A-Za-z])*([0-9])* ; char added
int index = s.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
string chars = s.Substring(0, index);
int num = Int32.Parse(s.Substring(index));
I really like jason's answer. Lets improve it a bit. We dont need regex here. My solution handle input like "H1N1":
public static IEnumerable<string> SplitAlpha(string input)
{
var words = new List<string> { string.Empty };
for (var i = 0; i < input.Length; i++)
{
words[words.Count-1] += input[i];
if (i + 1 < input.Length && char.IsLetter(input[i]) != char.IsLetter(input[i + 1]))
{
words.Add(string.Empty);
}
}
return words;
}
This solution is linear O(n).
output
"H1N1" -> ["H", "1", "N", "1"]
"H" -> ["H"]
"GH1N12" -> ["GH", "1", "N", "12"]
"OS234" -> ["OS", "234"]
Same solution with a StringBuilder
public static IEnumerable<string> SplitAlpha(string input)
{
var words = new List<StringBuilder>{new StringBuilder()};
for (var i = 0; i < input.Length; i++)
{
words[words.Count - 1].Append(input[i]);
if (i + 1 < input.Length && char.IsLetter(input[i]) != char.IsLetter(input[i + 1]))
{
words.Add(new StringBuilder());
}
}
return words.Select(x => x.ToString());
}
Try it Online!
If you want resolve more occurrences of char followed by number or vice versa you can use
private string SplitCharsAndNums(string text)
{
var sb = new StringBuilder();
for (var i = 0; i < text.Length - 1; i++)
{
if ((char.IsLetter(text[i]) && char.IsDigit(text[i+1])) ||
(char.IsDigit(text[i]) && char.IsLetter(text[i+1])))
{
sb.Append(text[i]);
sb.Append(" ");
}
else
{
sb.Append(text[i]);
}
}
sb.Append(text[text.Length-1]);
return sb.ToString();
}
And then
var text = SplitCharsAndNums("asd1 asas4gr5 6ssfd");
var tokens = text.Split(' ');
Are you doing this for sorting purposes? If so, keep in mind that Regex can kill performance for large lists. I frequently use an AlphanumComparer that's a general solution to this problem (can handle any sequence of letters and numbers in any order). I believe that I adapted it from this page.
Even if you're not sorting on it, using the character-by-character approach (if you have variable lengths) or simple substring/parse (if they're fixed) will be a lot more efficient and easier to test than a Regex.
I have used bniwredyc's answer to get Improved version of my routine:
private void demo()
{
string cell = "ABCD4321";
int row, a = getIndexofNumber(cell);
string Numberpart = cell.Substring(a, cell.Length - a);
row = Convert.ToInt32(Numberpart);
string Stringpart = cell.Substring(0, a);
}
private int getIndexofNumber(string cell)
{
int indexofNum=-1;
foreach (char c in cell)
{
indexofNum++;
if (Char.IsDigit(c))
{
return indexofNum;
}
}
return indexofNum;
}
.NET 2.0 compatible, without regex
public class Result
{
private string _StringPart;
public string StringPart
{
get { return _StringPart; }
}
private int _IntPart;
public int IntPart
{
get { return _IntPart; }
}
public Result(string stringPart, int intPart)
{
_StringPart = stringPart;
_IntPart = intPart;
}
}
class Program
{
public static Result GetResult(string source)
{
string stringPart = String.Empty;
int intPart;
var buffer = new StringBuilder();
foreach (char c in source)
{
if (Char.IsDigit(c))
{
if (stringPart == String.Empty)
{
stringPart = buffer.ToString();
buffer.Remove(0, buffer.Length);
}
}
buffer.Append(c);
}
if (!int.TryParse(buffer.ToString(), out intPart))
{
return null;
}
return new Result(stringPart, intPart);
}
static void Main(string[] args)
{
Result result = GetResult("OS234");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
result = GetResult("AA4230 ");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
result = GetResult("ABCD4321");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
Console.ReadKey();
}
}
Just use the substring function and set position inside the bracket.
String id = "DON123";
System.out.println("Id nubmer is : "+id.substring(3,6));
Answer:
Id number is: 123
use Split to seprate string from sting that use tab \t and space
string s = "sometext\tsometext\tsometext";
string[] split = s.Split('\t');
now you have an array of string that you want too easy

Categories