I created a program that uses both linear and binary search method. I use string array.
private void linearSearch_Click(object sender, EventArgs e)
{
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}
this will work, however the binary doest not
private void BinarySearch_Click(object sender, EventArgs e)
{
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if(numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target+ " is at index: " + numIndex;
}
}
test1 test2
Note that the code is performing a binary search in the text box of binarySearchBox, not the value in the text box of ListBox1.
The code that needs to convert the value added to ListBox1 into an Array array for storage.string[]myArray = listBox1.Items.Cast<string>().ToArray();,then search for ListBox1.
Code show as below:
private void BinarySearch_Click(object sender, EventArgs e)
{
string[]myArray = listBox1.Items.Cast<string>().ToArray();
Array.Sort(myArray, 0, emptyPtr);
SearchArray(myArray, binarySearchBox.Text);
}
private void SearchArray(Array array, object value)
{
string[] myArray = listBox1.Items.Cast<string>().ToArray();
Array.Sort(myArray, 0, emptyPtr);
string target = binarySearchBox.Text;
int numIndex = Array.BinarySearch(array, target);
if (numIndex < 0)
{
displayBox2.Text = "The element to search for " + target + " is not found.";
}
else if (numIndex >= 0)
{
displayBox2.Text = "The element to search for " + target + " is at index: " + numIndex;
}
}
private void linearSearch_Click(object sender, EventArgs e)
{
string[] myArray = listBox1.Items.Cast<string>().ToArray();
string target = linearSearchBox.Text;
bool found = false;
for (int x = 0; x < myArray.Length; x++)
{
if (myArray[x] == target)
{
displayBox2.Text = target + " Found at index " + (x + 1) +
"\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
return;
}
}
if (!found)
{
displayBox2.Text = "Not Found, try again." + "\r\n";
linearSearchBox.Clear();
linearSearchBox.Focus();
}
}
In RichTextBox, I'm trying to fire an event with pressing period ('.') But It's not working for the first time.
If I write "Lorem Ipsum.", It's not working but If I write "Lorem Ipsum ." or "Lorem Ipsum.." It's OK.
PS: I've added the KelimeGuncelle method and GetWordGroupInstances() dictionary also.
Here's the block:
private void rtbMakale_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod)
{
kelimeGuncelle();
}
}
The kelimeGuncelle method:
void kelimeGuncelle()
{
Dictionary<String, int> TekliKelimeGruplari = GetWordGroupInstances(1);
foreach (var item in TekliKelimeGruplari)
{
for (int i = 0; i < lstKelimeler.Items.Count; i++)
{
var kelime = lstKelimeler.Items[i];
string guncellenecekKelime = kelime.ToString().Remove(kelime.ToString().IndexOf(" ( ") - 1);
string gelenKelime = item.Key;
string _guncellenecekKelime = kelime.ToString();
int pFrom = _guncellenecekKelime.IndexOf("(") + 1;
int pTo = _guncellenecekKelime.LastIndexOf("/");
int guncellenecekSayi = Convert.ToInt32(_guncellenecekKelime.Substring(pFrom, pTo - pFrom));
int kFrom = _guncellenecekKelime.IndexOf("/") + 1;
int kTo = _guncellenecekKelime.LastIndexOf(")");
int toplamYazilacakSayi = Convert.ToInt32(_guncellenecekKelime.Substring(kFrom, kTo - kFrom));
int kelimeninSirasi = lstKelimeler.Items.IndexOf(kelime);
if (Equals(guncellenecekKelime, gelenKelime))
{
guncellenecekSayi = item.Value;
lstKelimeler.Items.RemoveAt(kelimeninSirasi);
lstKelimeler.Items.Insert(kelimeninSirasi, guncellenecekKelime + " ( " + guncellenecekSayi + "/" + toplamYazilacakSayi + " )");
//lstKelimeler.Refresh();
}
if (rtbMakale.Text.Contains(guncellenecekKelime) == false)
{
lstKelimeler.Items.RemoveAt(kelimeninSirasi);
lstKelimeler.Items.Insert(kelimeninSirasi, guncellenecekKelime + " ( 0/" + toplamYazilacakSayi + " )");
//lstKelimeler.Refresh();
}
}
}
TekliKelimeGruplari.Clear();
}
And GetWordGroupInstances:
Dictionary<String, int> GetWordGroupInstances(int GroupSize)
{
Dictionary<String, int> WordGroupInstances = new Dictionary<string, int>();
String[] sourceText = GetSourceText().Split(' ');
int pointer = 0;
StringBuilder groupBuilder = new StringBuilder();
while (pointer < sourceText.Length - GroupSize)
{
groupBuilder.Clear();
int offset = pointer + GroupSize;
for (int i = pointer; i < offset; i++)
{
groupBuilder.Append(" ").Append(sourceText[i]);
}
String key = groupBuilder.ToString().Substring(1);
if (!WordGroupInstances.ContainsKey(key))
{
WordGroupInstances.Add(key, 1);
}
else
{
WordGroupInstances[key]++;
}
pointer += 1;
}
return WordGroupInstances;
}
try using a MessageBox.Show("Test"); for testing , maybe something in your kelimeGuncelle() method is wrong.
private void rtbMakale_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.OemPeriod)
{
MessageBox.Show("Test");
}
}
I got it!
In the GetWordGroupInstances, I've changed the while loop. Here:
while (pointer <= sourceText.Length - GroupSize)
So I have a list of strings like so:
var drinks = new List(){"Drinks", " * ", "Rum", "Captain Morgan", "Kraken", " * ", "Whiskey",
"Laphroaig"}
It needs to return the following:
*Drinks
*Drinks * Rum
*Drinks * Rum * Captain Morgan
*Drinks * Rum * Kraken
*Drinks * Whiskey
*Drinks * Whiskey * Laphroaig
So as seen, anytime a * is encountered, the next string would be treated as a child under the root. So here, Rum would fall under Drinks and Captain Morgan and Kraken would fall under Rum. Whiskey would fall under Drinks and Laphroaig would fall under whiskey.
I know it has to be some sort of tree structure and the only thing I have right now is this:
private static Drink GroupDrinks(List<string> drinkNames)
{
var drink = new Drink() { Children = new List<Drink>() };
foreach (var drinkName in drinkNames)
{
if (drinkName != "*")
{
drink.Name = drinkName;
drinkNames.RemoveAt(0);
}
else
{
drinkNames.RemoveAt(0);
drink.Children.Add(GroupDrinks(drinkNames));
}
}
return drink;
}
I figured I'd need to do some kind of recursion and maybe remove the character so it doesn't affect the next iteration but this clearly isn't working. Any tips would be great.
I am not sure if this code work for you but it is tested as your expected output:
Declaration:
List<Drink> lstdrink = new List<Drink>();
public List<FinalDrink> lstFinalDrink = new List<FinalDrink>();
Class:
public class FinalDrink
{
public string name { get; set; }
}
public class Drink
{
public string name { get; set; }
public int Tag { get; set; }
}
Set Up the Value:
public List<Drink> SetUpTheValue()
{
var drinks = new List<string> { "Drinks", " * ", "Rum", "Captain Morgan", "Kraken", " * ", "Whiskey", "Laphroaig" };
var repl = drinks.Select(s => s.Replace('*', ' ')).ToList();
string tag = string.Empty;
Drink drk = new Drink();
lstdrink = new List<Drink>();
for (int i = 0; i < repl.Count; i++)
{
if (i == 0)
{
drk = new Drink();
drk.name = repl[i];
drk.Tag = 1;
lstdrink.Add(drk);
tag = repl[i];
continue;
}
if (tag.Trim().Length == 0)
{
drk = new Drink();
drk.name = repl[i];
drk.Tag = 2;
lstdrink.Add(drk);
tag = repl[i];
continue;
}
if (repl[i].ToString().Trim().Length > 0)
{
drk = new Drink();
drk.name = repl[i];
drk.Tag = 0;
lstdrink.Add(drk);
tag = repl[i];
}
tag = repl[i];
}
return lstdrink;
}
Group Drinks:
public List<FinalDrink> GroupDrinks(List<Drink> drinkNames)
{
lstFinalDrink = new List<FinalDrink>();
FinalDrink fDrink = new FinalDrink();
var GetFirst = drinkNames.Where(x => x.Tag == 1).ToList();
fDrink.name = GetFirst[0].name.ToString();
lstFinalDrink.Add(fDrink);
var Content = drinkNames.Where(x => x.Tag != 1).ToList();
string itrVal = string.Empty;
int prev = 0;
string hcur = string.Empty;
for (int i = 0; i < Content.Count(); i++)
{
if (Content[i].Tag == 2)
{
hcur = GetFirst[0].name + " * " + Content[i].name;
fDrink = new FinalDrink();
itrVal = GetFirst[0].name + " * " + Content[i].name;
fDrink.name = itrVal;
lstFinalDrink.Add(fDrink);
prev = Content[i].Tag;
itrVal = string.Empty;
}
else
{
fDrink = new FinalDrink();
itrVal = hcur + " * " + Content[i].name;
fDrink.name = itrVal;
lstFinalDrink.Add(fDrink);
prev = Content[i].Tag;
itrVal = string.Empty;
}
}
return lstFinalDrink;
}
Execution:
private void button1_Click(object sender, EventArgs e)
{
if (SetUpTheValue().Count() > 0)
{
GroupDrinks(lstdrink);
}
}
The GroupDrinks return List<FinalDrink> this is the final result.
It is depend on you to modify the result
This Code will return the expected output as you added from above.
i use the Asynchronous socket Client event to receive message from server.
i receive message from client DataIn(my Event Name) and add to list box ,but not happen to show on UI!
protected void WebSocketClientControl1_OnChatNotification(List < SocketUi > sender) {
ClientScript.RegisterStartupScript(GetType(), "hwa", "javascript:__doPostBack('WebSocketClientControl1','')", true);
}
i cant use the (Response.Redirect & Server.Transfer).
this 2 function have error run time.
i call the javaScript function to show message , not happen on screen.
its my Socket code
public delegate void OnChatNotification(List<SocketUi> sender);
public class WebSocketClientControl : System.Web.UI.Control, IPostBackDataHandler
{
public static ClientService _internalClientService = new ClientService(DServerConfig.ServerAddress.ToString(),
DServerConfig.ServerSoketPort);
public event OnChatNotification OnChatNotification = delegate { };
public WebSocketClientControl()
{
_internalClientService.OnChat += _internalClientService_OnChat;
}
public void Connect(long userID, SocketEnums.EntityType usertype, string username, string key)
{
_internalClientService.Connect(userID, usertype, username, key);
}
private void _internalClientService_OnChat(List<SocketUI.SocketUi> sender)
{
if (OnChatNotification != null)
OnChatNotification(sender);
}
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
String presentValue = postDataKey;
String postedValue = postCollection[postDataKey];
if (presentValue == null || !presentValue.Equals(postedValue))
{
return true;
}
return false;
}
public void RaisePostDataChangedEvent()
{
}
}
its my ui Code
private void WebSocketClientControl1_OnChatNotification(List<SocketUI.SocketUi> sender)
{
foreach (SocketUi socketUi in sender)
{
switch (socketUi.DSocketType)
{
case SocketEnums.DSocketType.Chat:
foreach (SocketUI.tb_Chat chatUi in socketUi.Chats)
{
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
if (ASPxPageControl1.TabPages[i].Name == "uxTabPage_" + _channels[i].ID.ToString())
{
switch (chatUi.ChatMessegeType)
{
case (int)Enums.ChatMessegeType.Message:
SetNewMessageOnUi(HelperD.UiChat_To_Tb_Chat(chatUi));
break;
case (int)Enums.ChatMessegeType.Readed:
break;
case (int)Enums.ChatMessegeType.OnLinedUser:
break;
case (int)Enums.ChatMessegeType.OffLinedUser:
break;
case (int)Enums.ChatMessegeType.JoinChannle:
case (int)Enums.ChatMessegeType.LeftChannle:
GetUserChannel(chatUi.ChannelID.ID);
break;
case (int)Enums.ChatMessegeType.TypingUser:
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.Label &&
ASPxPageControl1.TabPages[i].Controls[j].ID ==
"uxLabel_Status" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.Label uxLabel_StatusTemp = new System.Web.UI.WebControls.Label();
uxLabel_StatusTemp = (System.Web.UI.WebControls.Label)ASPxPageControl1.TabPages[i].Controls[j];
uxLabel_StatusTemp.Text = " درحال تایپ " + socketUi.UserName + "...";
// timer1.Start();
}
}
break;
}//End For
// listBox_Message.Items.Add("Me:=>" + chatUi.Message + "\n\r");
}
}
}//End For
break;
}
}
}
private void SetNewMessageOnUi(UiSideLanguage.Database.Chat.tb_Chat item)
{
ASPxTextBox_Message.Text = "";
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.ListBox && ASPxPageControl1.TabPages[i].Controls[j].ID == "uxListView_Chat" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.ListBox userListView = (System.Web.UI.WebControls.ListBox)ASPxPageControl1.TabPages[i].Controls[j];
System.Web.UI.WebControls.ListItem listViewItemTemp = new System.Web.UI.WebControls.ListItem();
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
listViewItemTemp.Text = " :من " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkCyan;
}
else
{
listViewItemTemp.Text = item.AddUser.UserName + " : " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkRed;
}
listViewItemTemp.Value = item.MessageFlagID.ToString();
System.Web.UI.WebControls.ListItem isHaveChatItem = null;
foreach (System.Web.UI.WebControls.ListItem chatitemListView in userListView.Items)
{
if (Language.HelperD.GetLong(chatitemListView.Value) == item.MessageFlagID)
{
isHaveChatItem = chatitemListView;
break;
}
}
if (isHaveChatItem != null)
{
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
isHaveChatItem.Text = " :من " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkCyan;
}
else
{
isHaveChatItem.Text = item.ToUser.UserName + " : " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkRed;
}
isHaveChatItem.Value = item.MessageFlagID.ToString();
}
else
{
userListView.Items.Add(listViewItemTemp);
}
}
}
}
}
This function for Update UI >>> SetNewMessageOnUi
I Create Objects on Runtime.
this code is worked
userListView.Items.Add(listViewItemTemp);
and ListView Have Item But On UI Not set.
all objects in the UpdatePanle
I'm writing a function to take shorthand values and convert them into a standardized numeric format. Is there any standard code out there that would do "best possible" conversion of arbitrary measurement text and turn it into numeric measurements if the text is valid?
I guess I'm looking for something like bool TryParseMeasurement(string s, out decimal d). Does anyone know of a function like this?
Here's an example of some of the input values I've seen:
Imperial
6 inches
6in
6”
4 feet 2 inches
4’2”
4 ‘ 2 “
3 feet
3’
3 ‘
3ft
3ft10in
3ft 13in (should convert to 4’1”)
Metricc
1m
1.2m
1.321m
1 meter
481mm
Here's some code we wrote in an app quite some time ago, where we were doing something similar. It's not the best, but you may be able to adapt, or get some sort of jumping off point.
public static class UnitConversion
{
public static string[] lstFootUnits = new string[] {"foots", "foot", "feets", "feet", "ft", "f", "\""};
public static string sFootUnit = "ft";
public static string[] lstInchUnits = new string[] { "inches", "inchs", "inch", "in", "i", "\'" };
public static string sInchUnit = "in";
public static string[] lstPoundUnits = new string[] { "pounds", "pound", "pnds", "pnd", "lbs", "lb", "l", "p" };
public static string sPoundUnit = "lbs";
public static string[] lstOunceUnits = new string[] { "ounces", "ounce", "ozs", "oz", "o" };
public static string sOunceUnit = "oz";
public static string[] lstCentimeterUnits = new string[] { "centimeters", "centimeter", "centimetres", "centimetre", "cms", "cm", "c"};
public static string sCentimeterUnit = "cm";
public static string[] lstKilogramUnits = new string[] { "kilograms", "kilogram", "kilos", "kilo", "kgs", "kg", "k" };
public static string sKilogramsUnit = "kgs";
/// <summary>
/// Attempt to convert between feet/inches and cm
/// </summary>
/// <param name="sHeight"></param>
/// <returns></returns>
public static string ConvertHeight(string sHeight)
{
if (!String.IsNullOrEmpty(sHeight))
{
sHeight = UnitConversion.CleanHeight(sHeight);
if (sHeight.Contains(UnitConversion.sFootUnit))
{
sHeight = sHeight.Replace(UnitConversion.sFootUnit, "|");
sHeight = sHeight.Replace(UnitConversion.sInchUnit, "|");
string[] sParts = sHeight.Split('|');
double? dFeet = null;
double? dInches = null;
double dFeetParsed;
double dInchesParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dFeetParsed))
{
dFeet = dFeetParsed;
}
if (sParts.Length >= 4 && double.TryParse(sParts[2].Trim(), out dInchesParsed))
{
dInches = dInchesParsed;
};
sHeight = UnitConversion.FtToCm(UnitConversion.CalculateFt(dFeet ?? 0, dInches ?? 0)).ToString() + " " + UnitConversion.sCentimeterUnit;
}
else if (sHeight.Contains(UnitConversion.sCentimeterUnit))
{
sHeight = sHeight.Replace(UnitConversion.sCentimeterUnit, "|");
string[] sParts = sHeight.Split('|');
double? dCentimeters = null;
double dCentimetersParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dCentimetersParsed))
{
dCentimeters = dCentimetersParsed;
}
int? iFeet;
int? iInches;
if (UnitConversion.CmToFt(dCentimeters, out iFeet, out iInches))
{
sHeight = (iFeet != null) ? iFeet.ToString() + " " + UnitConversion.sFootUnit : "";
sHeight += (iInches != null) ? " " + iInches.ToString() + " " + UnitConversion.sInchUnit : "";
sHeight = sHeight.Trim();
}
else
{
sHeight = "";
}
}
else
{
sHeight = "";
}
}
else
{
sHeight = "";
}
return sHeight;
}
/// <summary>
/// Attempt to convert between Kgs and Lbs
/// </summary>
/// <param name="sWeight"></param>
/// <returns></returns>
public static string ConvertWeight(string sWeight)
{
if (!String.IsNullOrEmpty(sWeight))
{
sWeight = UnitConversion.CleanWeight(sWeight);
if (sWeight.Contains(UnitConversion.sKilogramsUnit))
{
sWeight = sWeight.Replace(UnitConversion.sKilogramsUnit, "|");
string[] sParts = sWeight.Split('|');
double? dKilograms = null;
double dKilogramsParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dKilogramsParsed))
{
dKilograms = dKilogramsParsed;
}
sWeight = UnitConversion.KgToLbs(dKilograms).ToString("#.###") + " " + UnitConversion.sPoundUnit;
}
else if (sWeight.Contains(UnitConversion.sPoundUnit))
{
sWeight = sWeight.Replace(UnitConversion.sPoundUnit, "|");
string[] sParts = sWeight.Split('|');
double? dPounds = null;
double dPoundsParsed;
if (sParts.Length >= 2 && double.TryParse(sParts[0].Trim(), out dPoundsParsed))
{
dPounds = dPoundsParsed;
}
sWeight = UnitConversion.LbsToKg(dPounds).ToString("#.###") + " " + UnitConversion.sKilogramsUnit;
}
else
{
sWeight = "";
}
}
else
{
sWeight = "";
}
return sWeight;
}
public static double? CalculateFt(double dFt, double dInch)
{
double? dFeet = null;
if (dFt >= 0 && dInch >= 0 && dInch <= 12)
{
dFeet = dFt + (dInch / 12);
}
return dFeet;
}
public static double KgToLbs(double? dKg)
{
if (dKg == null)
{
return 0;
}
return dKg.Value * 2.20462262;
}
public static double LbsToKg(double? dLbs)
{
if (dLbs == null)
{
return 0;
}
return dLbs.Value / 2.20462262;
}
public static double FtToCm(double? dFt)
{
if (dFt == null)
{
return 0;
}
return dFt.Value * 30.48;
}
public static bool CmToFt(double? dCm, out int? iFt, out int? iInch)
{
if (dCm == null)
{
iFt = null;
iInch = null;
return false;
}
double dCalcFeet = dCm.Value / 30.48;
double dCalcInches = dCalcFeet - Math.Floor(dCalcFeet);
dCalcFeet = Math.Floor(dCalcFeet);
dCalcInches = dCalcInches * 12;
iFt = (int)dCalcFeet;
iInch = (int)dCalcInches;
return true;
}
private static string CleanUnit(string sOriginal, string[] lstReplaceUnits, string sReplaceWithUnit)
{
System.Text.StringBuilder sbPattern = new System.Text.StringBuilder();
foreach (string sReplace in lstReplaceUnits)
{
if (sbPattern.Length > 0)
{
sbPattern.Append("|");
}
sbPattern.Append(sReplace);
}
sbPattern.Insert(0,#"(^|\s)(");
sbPattern.Append(#")(\s|$)");
System.Text.RegularExpressions.Regex rReplace = new System.Text.RegularExpressions.Regex(sbPattern.ToString(), System.Text.RegularExpressions.RegexOptions.IgnoreCase);
sOriginal = rReplace.Replace(sOriginal, sReplaceWithUnit);
/*foreach (string sReplace in lstReplaceUnits)
{
sOriginal = sOriginal.Replace(sReplace, " " + sReplaceWithUnit);
}*/
return sOriginal;
}
private static bool StringHasNumbers(string sText)
{
System.Text.RegularExpressions.Regex rxNumbers = new System.Text.RegularExpressions.Regex("[0-9]+");
return rxNumbers.IsMatch(sText);
}
private static string ReduceSpaces(string sText)
{
while (sText.Contains(" "))
{
sText = sText.Replace(" ", " ");
}
return sText;
}
private static string SeperateNumbers(string sText)
{
bool bNumber = false;
if (!String.IsNullOrEmpty(sText))
{
for (int iChar = 0; iChar < sText.Length; iChar++)
{
bool bIsNumber = (sText[iChar] >= '0' && sText[iChar] <= '9') ||
(sText[iChar] == '.' && iChar < sText.Length - 1 && sText[iChar + 1] >= '0' && sText[iChar + 1] <= '9');
if (iChar > 0 && bIsNumber != bNumber)
{
sText = sText.Insert(iChar, " ");
iChar++;
}
bNumber = bIsNumber;
}
}
return sText;
}
public static string CleanHeight(string sHeight)
{
if (UnitConversion.StringHasNumbers(sHeight))
{
sHeight = SeperateNumbers(sHeight);
sHeight = CleanUnit(sHeight, UnitConversion.lstFootUnits, UnitConversion.sFootUnit);
sHeight = CleanUnit(sHeight, UnitConversion.lstInchUnits, UnitConversion.sInchUnit);
sHeight = CleanUnit(sHeight, UnitConversion.lstCentimeterUnits, UnitConversion.sCentimeterUnit);
sHeight = SeperateNumbers(sHeight);
sHeight = ReduceSpaces(sHeight);
}
else
{
sHeight = "";
}
return sHeight;
}
public static string CleanWeight(string sWeight)
{
if (UnitConversion.StringHasNumbers(sWeight))
{
sWeight = SeperateNumbers(sWeight);
sWeight = CleanUnit(sWeight, UnitConversion.lstOunceUnits, UnitConversion.sOunceUnit);
sWeight = CleanUnit(sWeight, UnitConversion.lstPoundUnits, UnitConversion.sPoundUnit);
sWeight = CleanUnit(sWeight, UnitConversion.lstKilogramUnits, UnitConversion.sKilogramsUnit);
sWeight = SeperateNumbers(sWeight);
sWeight = ReduceSpaces(sWeight);
}
else
{
sWeight = "";
}
return sWeight;
}
}
It should serve you well to build an extension method of string for this purpose. When you build an extension method you attach a new function call to an existing class. In this we are go to attach a method to the 'string' class that returns a double, as the number of millimeters in a given imperial value, PROVIDED that the value can be parsed based on the examples you provide.
using System;
using System.Text;
namespace SO_Console_test
{
static class ConversionStringExtensions
{
//this is going to be a simple example you can
//fancy it up a lot...
public static double ImperialToMetric(this string val)
{
/*
* With these inputst we want to total inches.
* to do this we want to standardize the feet designator to 'f'
* and remove the inch designator altogether.
6 inches
6in
6”
4 feet 2 inches
4’2”
4 ‘ 2 “
3 feet
3’
3 ‘
3ft
3ft10in
3ft 13in (should convert to 4’1”) ...no, should convert to 49 inches, then to metric.
*/
//make the input lower case and remove blanks:
val = val.ToLower().Replace(" ", string.Empty);
//make all of the 'normal' feet designators to "ft"
string S = val.Replace("\'", "f").Replace("feet", "f").Replace("ft", "f").Replace("foot", "f").Replace("‘", "f").Replace("’", "f");
//and remove any inch designator
S = S.Replace("\"", string.Empty).Replace("inches", string.Empty).Replace("inch", string.Empty).Replace("in", string.Empty).Replace("“", string.Empty).Replace("”", string.Empty);
//finally we have to be certain we have a number of feet, even if that number is zero
S = S.IndexOf('f') > 0 ? S : "0f" + S;
//now, any of the inputs above will have been converted to a string
//that looks like 4 feet 2 inches => 4f2
string[] values = S.Split('f');
int inches = 0;
//as long as this produces one or two values we are 'on track'
if (values.Length < 3)
{
for (int i = 0; i < values.Length; i++)
{
inches += values[i] != null && values[i] != string.Empty ? int.Parse(values[i]) * (i == 0 ? 12 : 1) : 0 ;
}
}
//now inches = total number of inches in the input string.
double result = inches * 25.4;
return result;
}
}
}
With that in place "ImperialToMetric()" becomes a method of any string, and can be invoked anywhere the extension containing class ConversionStringExtensions is referenced. You can use it like:
namespace SO_Console_test
{
class Program
{
static void Main(string[] args)
{
showConversion();
Console.ReadLine();
}
private static void showConversion()
{
//simple start:
Console.WriteLine("6ft 2\"".ImperialToMetric().ToString() + " mm");
//more robust:
var Imperials = new List<string>(){"6 inches",
"6in",
"6”",
"4 feet 2 inches",
"4’2”",
"4 ‘ 2 “",
"3 feet",
"3’",
"3 ‘",
"3ft",
"3ft10in",
"3ft 13in"};
foreach (string imperial in Imperials)
{
Console.WriteLine(imperial + " converted to " + imperial.ImperialToMetric() + " millimeters");
}
}
}
Obviously, at this point a call to "Fred".ImperialToMetric is not going to play nice. You will need to had error handling and perhaps some options to turn 1234 mm 1.234 km etc. but once you flush this out you have a method you can use where ever you choose.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
double km,m,f,i,cm;
Console.WriteLine("The distance between karachi and lahore in (kilometer)km is=");
km = Convert.ToInt32(Console.ReadLine());
m = km * 1000;
Console.WriteLine("The distance between karachi and lahore in meter(m) is="+m);
f = km * 3280.84;
Console.WriteLine("The distance between karachi and lahore in feet(f) is="+f);
i = km * 39370.1;
Console.WriteLine("The distance between karachi and lahore in inches(i) is="+i);
cm = m * 100;
Console.WriteLine("The distance between karachi and lahore in centimeter(cm) is="+cm);
Console.ReadLine();
}
}
}
An extension for string I wrote only to find out that there is already a solution here :) The only thing left to do is to replace "feet", "ft", "’" to "'" and "inches", "inch", "in", "“", "\"" to "''".
using System;
namespace CustomExtensions
{
public static class StringExtension
{
const float mPerFeet = 30.48f / 100;
const float mPerInch = 2.54f / 100;
// input options:
// 5'
// 5'6''
// 18''
// 24''
// 5'6
// 5 ' 6 ''
// 5' 6''
// corner cases:
// '' will return 0
// 5''6'' will interpret as 5'6''
// 5'6' will interpret as 5'6''
// 6 will interpret as 6''
// 6''' will interpret as 6''
public static float MetersFromFeetInches(this string feetInches)
{
float feet = 0;
float inches = 0;
string[] separators = new string[] { "'", "''", " " };
string[] subs = feetInches.Split(separators, StringSplitOptions.RemoveEmptyEntries);
if (subs.Length == 1)
{
if (feetInches.Trim().EndsWith("''"))
{
float.TryParse(subs[0], out inches);
}
else if (!feetInches.Trim().EndsWith("''") && !feetInches.Trim().EndsWith("'"))
{
float.TryParse(subs[0], out inches);
}
else
{
float.TryParse(subs[0], out feet);
}
}
else if (subs.Length > 1)
{
float.TryParse(subs[0], out feet);
float.TryParse(subs[1], out inches);
}
return feet * mPerFeet + inches * mPerInch;
}
}
}