Find specific part of string based on condition - c#

I have below comma separated string. This string contains relation which is needed in the application for processing.
string userInputColRela = "input1:Student_Name, input2:Student_Age";
Now, i need to extract Student_Name if i provide input as input1 and Student_Age if the input provided is input2.
How can i achieve this? I know i can go with looping but that will be a little lengthy solution, what is other way round?

You could parse the input string by splitting firstly on the comma, then again on the semi-colon to get the key-value pairs contained in it in dictionary form. For example:
string userInputColRela = "input1: Student_Name, input2: Student_Age";
var inputLookup = userInputColRela
.Split(',')
.Select(a => a.Split(':'))
.ToDictionary(a => a[0].Trim(), a => a[1].Trim());
var studentName = inputLookup["input1"];

If your strings are always in the format input1:Student_Name, input2:Student_Age then probably you can use a Dictionary<k,v> and Split() function like
string userInputColRela = "input1:Student_Name, input2:Student_Age";
string input = "input1";
var args = userInputColRela.Split(',');
Dictionary<string, string> inputs = new Dictionary<string, string>();
foreach (var item in args)
{
var data = item.Split(':');
inputs.Add(data[0], data[1]);
}
Console.WriteLine(inputs[input]);

Related

How can I Read Dynamic String and Store each key string Value into a varaible?

This is my dynamic String:
String a= "SourceFilePath:C:\Users\Anuj\Desktop\Anuj Tamrakar Working Folder, BackUpFilePath:C:\Users\Anuj\Desktop\installer, SyncPath:C:\Users\Anuj\Desktop\PSI, Password:3SMpUGoJpIJdWwRDXau+OQ==, NumberOfTimes:2, Time0:10:10 AM, Time1:10:10 PM"
I need to read the contents of the string and need to store each key and its coressponding values into variable. I need Output like
var SourceFilePath = "C:\Users\Anuj\Desktop\Anuj Tamrakar Working Folder";
var BackUpFilePath="C:\Users\Anuj\Desktop\installer"
var SyncPath="C:\Users\Anuj\Desktop\PSI"
var Password="3SMpUGoJpIJdWwRDXau+OQ=="
var NumberOfTimes=2
var Time0=10:10 AM
var Time1=10:10 PM
This Part is Dynamic one:
var NumberOfTimes:2
var Time0:10:10 AM
var Time1:10:10 PM
If I have NumberOfTimes:4 on my String File. I would Have 4 Time values i.e. Time0,Time1,Time2 and Time3. So i need to store these 4 time values into 4 variables
I tried this in a console app and works fine. Below is my solution.
static void Main(string[] args)
{
String a = #"SourceFilePath:C:\Users\Anuj\Desktop\Anuj Tamrakar Working Folder, BackUpFilePath:C:\Users\Anuj\Desktop\installer, SyncPath:C:\Users\Anuj\Desktop\PSI, Password:3SMpUGoJpIJdWwRDXau+OQ==, NumberOfTimes:2, Time0:10:10 AM, Time1:10:10 PM";
Dictionary<string, string> processedString = ProcessString(a);
//Here you can set the values to variable accessing it from the Dictionary
var SourceFilePath = processedString["SourceFilePath"];
var BackUpFilePath = processedString["BackUpFilePath"];
var SyncPath = processedString["SyncPath"];
var Password = processedString["Password"];
var NumberOfTimes = Convert.ToInt32(processedString["NumberOfTimes"]);
// And for the dynamic variables like Time01, Time02 I recommend you to create a list which holds all the time components.
// Because creating a variable on the fly will be more complex for your requirement and is not necessary at this moment.
//So you can do this
var TimeComponents = processedString.Where(x => x.Key.StartsWith("Time")).Select(x => x).ToList();
Console.ReadLine();
}
And the process of splitting up the string and creating a dictionary is as below.
public static Dictionary<string, string> ProcessString(string toProcess)
{
Dictionary<string, string> processedString = new Dictionary<string, string>();
var eachSubString = toProcess.Split(',');
foreach (var subStr in eachSubString)
{
var keyValue = subStr.Trim().Split(new char[] { ':' }, 2);
processedString.Add(keyValue[0], keyValue[1]);
}
return processedString;
}
And here is the screen shot of the debugger
Let me know if this helps.
You could use a dictionary object.
Split string input on , then loop through variable key value pairs splitting on :.
Store key and value in dictionary.
You don't need to declare each variable but you could look it up in the dictionary by the key.
It must be something like below.
// you can also fill an array dynamically
var NumberOfTimes=["10:10 AM","10:11 AM","10:12 AM"]
//count of stored items in array
NumberOfTimes.length
//in order to print or use in some where else
NumberOfTimes.forEach(function(e,i){
//do somethings
});

Parse String with delimiters to dictionary

I have a string formated so:
string-int,string-int,string-int
The data will always be as above, what i need to accomplish is splitting each string-int value into a dictionary. Does anyone have an efficient solution to accomplish this?
As i understand it directly splitting the string by the ',' then splitting each result by the '-' into a dictionary is ineffcient.
If you are absolutely assured that all data is correct you can use following:
split source string to the string[] by "," symbol;
for each element split it by "-" symbol;
for each resulted element (of string[][]) convert it to dictionary pair. Use first element [0] as a key and cast second element [1] to integer as a value;
Dictionary<string, int> dictionary = sourceString
.Split(',')
.Select(element => element.Split('-'))
.ToDictionary(pair => pair[0], pair => int.Parse(pair[1]));
Try following .
var input = "string-1,string2-2,string3-3";
var splittedByComma = input.Split(',').ToList();
var dictionary = new Dictionary<string, int>();
splittedByComma.ForEach(sp => dictionary.Add(sp.Split('-')[0], int.Parse(sp.Split('-')[1])));
static Dictionary<string, int> convert(string s)
{
var t = new Dictionary<string, int>();
t.Add(s.Split('-')[0], System.Convert.ToInt32(s.Split('-')[1]));
return t;
}
var t = "\"test\"-123,\"test\"-123";
var d = t.Split(',').Select(convert);

replacing data in between specific characters

I have a string which has some keys between <<>>.
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>";
I want to first fetch the key names USER and SENDER in a list which i did by:
var keys = new List<string>();
foreach (Match match in Regex.Matches(s, #"<<(.*?)>>"))
{
keys.Add(match.Groups[1].Value);
}
List<string> values= new List<string>(){"John","Team"};
After we get the keys,i want to replace these keys by another list(named values here) which has the values for these keys and want the result as:
string s = "<p>Hi John,<br/>How are you doing<br/>Regards,<br/>Team</p>";
The string s can be anything and the no of keys and their values could also vary but the keys will always be enclosed in between <<>>
As suggested by #AlexBell, you could simply use the String.Replace() method.
Further, it's more convenient to declare a collection of placeholder/value pairs, like so:
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>";
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("<<USER>>", "Jhon");
dictionary.Add("<<SENDER>>", "Team");
StringBuilder text = new StringBuilder(s);
foreach (var entry in dictionary)
{
text.Replace(entry.Key, entry.Value);
}
Console.WriteLine(text.ToString());
This function will perform the replacements that you ask for, using Regex.Replace:
public static string ParseTemplate(string template, string username, string senderName)
{
template = Regex.Replace(template, #"<<USER>>", username);
return Regex.Replace(template, #"<<SENDER>>", senderName);
}
Example:
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>";
ParseTemplate(s, "John", "Team").Dump();
Output:
<p>Hi John,<br/>How are you doing<br/>Regards,<br/>Team</p>
You can call this in a loop over your dictionary or list of names.
Your business logic is a bit unclear, so based on just qualified guess, you can apply standard .NET/C# String.Replace Method (String, String)
(re:https://msdn.microsoft.com/en-us/library/fk49wtc1%28v=vs.110%29.aspx), for example:
string s = "<p>Hi <<USER>>,<br/>How are you doing<br/>Regards,<br/><<SENDER>></p>".Replace("<USER>", "John").Replace("<SENDER>", "Team");
Hope this may help.
//First we have lists of values (users) and senders
List<string> values= new List<string>(){"John","Team"};
List<string> senders = new List<string>(){"John","Team"};
//Then we can join that list using string.join
var allUsers = string.Join(",", values);
var allSender = string.Join(",", senders);
//Next we will be replacing it in our string
var namedString = Regex.Replace(string, #"<<USER>>", allUsers);
var output = Regex.Replace(namedString , #"<<SENDER>>", allSender);

String parsing C# creating segments?

I have a string in the form of:
"company=ABCorp, location=New York, revenue=10million, type=informationTechnology"
I want to be able to parse this string out and get "name", "value" pairs in the form of
company = ABCCorp
location= New York etc.
This could be any suitable data structure to store. I was thinking maybe a Dictionary<string, string>() but im open to suggestions.
Is there a suitable way of doing this in C#?
EDIT: My final goal here is to have something like this:
Array[company] = ABCCorp.
Array[location] = New York.
What data structure could we use to achieve the above? MY first thought is a Dictionary but I am not sure if Im missing anything.
thanks
Using String.Split and ToDictionary, you could do:
var original = "company=ABCorp, location=New York, revenue=10million, type=informationTechnology";
var split = original.Split(',').Select(s => s.Trim().Split('='));
Dictionary<string,string> results = split.ToDictionary(s => s[0], s => s[1]);
string s = "company=ABCorp, location=New York, revenue=10million, type=informationTechnology";
var pairs = s.Split(',')
.Select(x => x.Split('='))
.ToDictionary(x => x[0], x => x[1]);
pairs is Dictionary with the key value pair. The only caveat is you will probably want to deal with any white space between the comma and the string.
It depends a lot on the expected syntax. One way to do this is to use String.Split:
http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
First split on comma, then iterate over all items in the string list returned and split those on equality.
However, this requires that comma and equality are never present in the values?
I'm assuming a weak RegEx/LINQ background so here's a way to do it without anything "special".
string text = "company=ABCorp, location=New York, revenue=10million, type=informationTechnology";
string[] pairs = text.Split(',');
Dictionary<string, string> dictData = new Dictionary<string, string>();
foreach (string currPair in pairs)
{
string[] data = currPair.Trim().Split('=');
dictData.Add(data[0], data[1]);
}
This has the requirement that a comma (,) and an equal-sign (=) never exist in the data other than as delimiters.
This relies heavily on String.Split.

How can you change a ";" seperated string to some kind of dictionary?

I have a string like this:
"user=u123;name=Test;lastname=User"
I want to get a dictionary for this string like this:
user "u123"
name "Test"
lastname "User"
this way I can easely access the data within the string.
I want to do this in C#.
EDIT:
This is what I have so far:
public static Dictionary<string, string> ValueToDictionary(string value)
{
Dictionary<string, string> result = null;
result = new Dictionary<string, string>();
string[] values = value.Split(';');
foreach (string val in values)
{
string[] valueParts = val.Split('=');
result.Add(valueParts[0], valueParts[1]);
}
return result;
}
But to be honest I really think there is a better way to do this.
Cheers,
M.
You can use LINQ:
var text = "user=u123;name=Test;lastname=User";
var dictionary = (from t in text.Split( ";".ToCharArray() )
let pair = t.Split( "=".ToCharArray(), 2 )
select pair).ToDictionary( p => p[0], p => p[1] );
Split the string by ";".
Iterate over every element in the resulting array and split every element by "=".
Now;
dictionary.add(element[0], element[1]);
I Hope I made it clear enough.
Dictionary<string, string> d = new Dictionary<string, string>();
string s1 = "user=u123;name=Test;lastname=User";
foreach (string s2 in s1.Split(';'))
{
string[] split = s2.Split('=');
d.Add(split[0], split[1]);
}
var dictionary = new Dictionary<string, string>();
var linedValue = "user=u123;name=Test;lastname=User";
var kvps = linedValue.Split(new[] { ';' }); // you may use StringSplitOptions.RemoveEmptyEntries
foreach (var kvp in kvps)
{
var kvpSplit = kvp.Split(new[] { '=' });
var key = kvpSplit.ElementAtOrDefault(0);
var value = kvpSplit.ElementAtOrDefault(1);
dictionary.Add(key, value);
// you may check with .ContainsKey if key is already persistant
// you may check if key and value with string.IsNullOrEmpty
}
If you know for sure that there are no separator chars in your input data, the following works
string input = "user=u123;name=Test;lastname=User";
string[] fragments = input.Split(";=".ToArray());
Dictionary<string,string> result = new Dictionary<string,string>()
for(int i=0; i<fragments.Length-1;i+=2)
result.Add(fragments[i],fragments[i+1]);
It might perform slightly better than some of the other solutions, since it only calls Split() once. Usually I would go for any of the other solutions here, especially if readability of the code is of any value to you.
I think I would do it like this...
String s = "user=u123;name=Test;lastname=User";
Dictionary<string,string> dict = s.ToDictionary();
The implementation of ToDictonary is the same as yours except that I would implement it as an extension method. It does look more natural.

Categories