c# - Replacing a substring consisting of a digit -
i'm newbie programmer sorry in advance if i'm asking too-obvious question.
i program in c#(wpf).
i have few strings built in structure:
string str ="david went location 1 have lunch"; string str2 ="mike has walk mile facing north reach location 2"; how can cut "location 1" out in elegant way replace string (that hold restaurant's name, continue example)??
i thought of doing like:
str.replace("location 1", strrestaurantname); but should generic(to allow replacement of location x), should using str.indexofto digit's position(it can number between 1 , 20), can't work...
oh, , unfortunately boss doesn't want me use regular expressions, or i'd have now.
thanks in advance.
you use dictionary like:
dictionary<string, string> restaurants = new dictionary<string, string>(); public form1() { initializecomponent(); restaurants.add("location 1", "abc restaurant"); restaurants.add("location 2", "abd restaurant"); restaurants.add("location 3", "abe restaurant"); restaurants.add("location 4", "abf restaurant"); restaurants.add("location 5", "abg restaurant"); } private void button1_click(object sender, eventargs e) { string str ="david went location 1 have lunch"; string str2 ="mike has walk mile facing north reach location 2"; messagebox.show( getrestaurant(str)); // result: david went abc restaurant have lunch messagebox.show( getrestaurant(str2)); // result: mike has walk mile facing north reach abd restaurant } private string getrestaurant(string msg) { string restaurantname = ""; foreach (string loc in restaurants.keys) { if (msg.contains(loc)) { restaurantname = msg.replace(loc, restaurants[loc]); break; } } return string.isnullorempty(restaurantname) ? msg : restaurantname; } and use linq shorten getrestaurant method this:
private string getrestaurant(string msg) { string restaurantname = restaurants.keys.firstordefault<string>(v => msg.contains(v)); return string.isnullorempty(restaurantname) ? msg : msg.replace(restaurantname, restaurants[restaurantname]); }
Comments
Post a Comment