Creating function syntax by manipulating string - c#

I am trying to create dynamic syntax function and function syntax is like below:
MyFunction( arg1,arg2,ar3.....);
I have string like this:
str = Previousvalue.Value1,Previousvalue.Value2
Now I would like to create syntax like this in final variable :
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);
str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
This is how I am trying to achieve with string.join (without using loop) but not getting how to do it and this seems like impossible to do without using loop:
final = string.Join("MyFunction(", str.Split(','));
Case 1:
Input : string str =Previousvalue.Value1,Previousvalue.Value2
Output:
string final=MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 2 :
Input : str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
output:
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 3:
string input = " Previousvalue.Value1";
Output:
String final = Previousvalue.Value1; //No function

From what I understand, you want to generate a string like this:
"MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);"
^..........^...................^....^...................^.
prefix arg1 sep arg2 suffix
or in other words
prefix = "MyFunction(";
separator = ",',',";
suffix = ");"
which can be achieved by moving the prefix and suffix out of the string.Join and using the above separator value:
string final = "MyFunction(" + string.Join(",',',", str.Split(',')) + ");";
Also instead of Split / Join you could simply use string.Replace:
string final = "MyFunction(" + str.Replace(",", ",',',") + ");";

From my understanding of the problem you want to call the MyFunction method with n string parameters, but also with string[]. You can do it like this:
public static void Main(string[] args)
{
string str = "Test1,Test2,Test3";
string test1 = MyFunction("Test1", "Test2", "Test3");
string test2 = MyFunction(str.Split(','));
}
public static string MyFunction(params string[] parameters)
{
StringBuilder sb = new StringBuilder();
foreach(var item in parameters)
{
sb.AppendLine(item);
}
return sb.ToString();
}

Try :
public string MyJoin(params string[] vars)
{
return "MyFunction(" + string.Join(",", vars) + ");";
}

Related

Dealing with multiple '.' in a file extension

I have this string that contains a filename
string filename = "C:\\Users\\me\\Desktop\\filename.This.Is.An.Extension"
I tried using the conventional
string modifiedFileName = System.IO.Path.GetFileNameWithoutExtension(filename);
but it only gets me:
modifiedFileName = "C:\\Users\\me\\Desktop\\filename.This.Is.An"
In order for me to get "C:\\Users\\me\\Desktop\\filename" I would have to use System.IO.Path.GetFileNameWithoutExtension several times, and that's just not efficient.
What better way is there to take my file name and have it return the directory + filename and no exceptions?
Many thanks in advance!
If you want to stop at the first period, you will have to handle it yourself.
Path.GetDirectoryName(filepath) + Path.GetFileName(filepath).UpTo(".")
using this string extension:
public static string UpTo(this string s, string stopper) => s.Substring(0, Math.Max(0, s.IndexOf(stopper)));
Take the directory and the base name:
var directoryPath = Path.GetDirectoryName(filename);
var baseName = Path.GetFileName(filename);
Strip the base name’s “extensions”:
var baseNameWithoutExtensions = baseName.Split(new[] {'.'}, 2)[0];
Recombine them:
var modifiedFileName = Path.Combine(directoryPath, baseNameWithoutExtensions);
demo
Without built in function:
public static void Main(string[] args)
{
string s = "C:\\Users\\me\\Desktop\\filename.This.Is.An.Extension";
string newString="";
for(int i=0;i<s.Length;i++)
{
if(s[i]=='.'){
break;
}else{
newString += s[i].ToString();
}
}
Console.WriteLine(newString); //writes "C:\Users\me\Desktop\filename"
}

Replace string after at with another string

I have two strings.
First string:
"31882757623"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738
Second string:vandrielfinance.nl
I want to replace asklync.nl to vandrielfinance.nl in the first string after the # with the second string (vandrielfinance.nl). Everything else will stay the same.
So the new string will be:
"31882757623"<sip:+31882757623#vandrielfinance.nl;user=phone>;epid=5440626C04;tag=daa784a738
Here is what I have so far:
static string ReplaceSuffix(string orginal, string newString)
{
string TobeObserved = "#";
orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
string pattern = second.Substring(0, second.LastIndexOf("#") + 1);
string code = orginal.Substring(orginal.IndexOf(TobeObserved) + TobeObserved.Length);
//newString = Regex.Replace(code,second, pattern);
newString = Regex.Replace(second, orginal, pattern);
string hallo = orginal.Replace(newString, second);
Console.Write("Original String: {0}", orginal);
Console.Write("\nReplacement String: \n{0}", newString);
Console.WriteLine("\n" + code);
return newString;
}
why not string.Replace?
string s = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string t = "vandrielfinance.nl";
string u = s.Replace("asklync.nl", t);
Console.WriteLine(u);
I'm not really a fan a string.Split(), but it made for quick work in this case:
static string ReplaceSuffix(string orginal, string newString)
{
var segments = original.Split(";".ToCharArray());
var segments2 = segments[0].Split("#".ToCharArray());
segments2[1] = newString;
segments[0] = string.Join("#", segments2);
var result = string.Join(";", segments);
Console.WriteLine("Original String:\n{0}\nReplacement String:\n{1}, original, result);
return result;
}
If the original domain will really always be asklync.nl, you may even be able to just do this:
static string ReplaceSuffix(string orginal)
{
var oldDomain = "asklync.nl";
var newDomain = "vandrielfinance.nl";
var result = original.Replace(oldDomain, newDomain);
Console.WriteLine("Original String:\n{0}\nReplacement String:\n{1}, original, result);
return result;
}
This should work
var orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
var returnValue = string.Empty;
var split = orginal.Split('#');
if (split.Length > 0)
{
var findFirstSemi = split[1].IndexOf(";");
var restOfString = split[1].Substring(findFirstSemi, split[1].Length - findFirstSemi);
returnValue = split[0] + "#" + second + restOfString;
}
Console.WriteLine("Original String:");
Console.WriteLine("{0}", orginal);
Console.WriteLine("Replacement String:");
Console.WriteLine("{0}", returnValue);
//return returnValue;
I'm not a huge fan of RegEx or string.Split, especially when a string function already exists to replace a portion of a string.
string orginal = "\"31882757623\"<sip:+31882757623#asklync.nl;user=phone>;epid=5440626C04;tag=daa784a738";
string second = "vandrielfinance.nl";
int start = orginal .IndexOf("#");
int end = orginal .IndexOf(";", start);
string newString = orginal .Replace(orginal.Substring(start, end-start), second );
Console.WriteLine(orginal );
Console.WriteLine(newString);

parsing a long string in c# and giving those values to parameters

I have this string in C# -
".... School||Abc\r\n...State||CA\r\n..."
The school and state are somewhere in the string. I need to parse the string in such a way that i get the values of School and State for my parameters
string school = abc (from String after parsing)
string state = CA (from string after parsing)
Try this:
string longStr = "School||Abc\r\nState||CA\r\n";
string[] keyValPairs = s.Split("\r\n".ToCharArray());
Dictionary<string, string> info = new Dictionary<string, string>();
foreach(string pair in keyValPairs)
{
string[] split = pair.Split("||");
//split[0] is the key, split[1] is the value
info.Add(split[0], split[1]);
}
Now you can access what you need like so:
string school = info["School"];
string state = info["State"];
Where the longStr variable is just your long string that you start out with, not neccessarily what I set it to.
Try split-ing string on new line chars and then it looks like a dictionary, with key values separated by ||. Another split on "||" should give you what you want.
Back of the envelope code
private static void ParseMyString(string longString) {
IEnumerable<string> shortStrings = longString.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach(var ss in shortStrings) {
var kvp = ss.Split("||".ToCharArray());
Console.WriteLine("{0} - {1}", kvp[0], kvp[1]);
}
}
You can use the TextFieldParser class to parse this file, in particular if it is fixed width fields or has known delimiters.
It:
Provides methods and properties for parsing structured text files.
Though it lives in the Microsoft.VisualBasic.Text namespace, it is a .NET assembly and can be used in all .NET projects.
Assuming that your string just contains values separated by "||", "\r" or "\n".
string str = "School||Abc\r\n||State||CA\r\n||AA||AA";
str = str.Trim();
str = str.Replace("\r",string.Empty);
str = str.Replace("\n", string.Empty);
string[] keyValue = str.Split(new string[] { "||" }, StringSplitOptions.None);
Dictionary<string, string> KeyValDic = new Dictionary<string, string>();
for (int i = 0; i < keyValue.Length; i++,i++)
{
KeyValDic.Add(keyValue[i], keyValue[i + 1]);
}

How do I use the Aggregate function to take a list of strings and output a single string separated by a space?

Here is the source code for this test:
var tags = new List<string> {"Portland", "Code","StackExcahnge" };
const string separator = " ";
tagString = tags.Aggregate(t => , separator);
Console.WriteLine(tagString);
// Expecting to see "Portland Code StackExchange"
Console.ReadKey();
Update
Here is the solution I am now using:
var tagString = string.Join(separator, tags.ToArray());
Turns out string.Join does what I need.
For that you can just use string.Join.
string result = tags.Aggregate((acc, s) => acc + separator + s);
or simply
string result = string.Join(separator, tags);
String.Join Method may be?
This is what I use
public static string Join(this IEnumerable<string> strings, string seperator)
{
return string.Join(seperator, strings.ToArray());
}
And then it looks like this
tagString = tags.Join(" ")

Build comma seperated string from the struct in C#

I have the following struct in C# class
public struct Employee
{
public const string EMPID = "EMP_ID";
public const string FName = "FIRST_NAME";
public const string LNAME = "LAST_NAME";
public const string DEPTID = "DEPT_ID";
}
Is there an easy way to build a string as follows
const string mainquery="INSERT INTO EMP(EMP_ID,FIRST_NAME,LAST_NAME,DEPT_ID) VALUES(:EMP_ID,:FIRST_NAME,:LAST_NAME,:DEPT_ID)"
Instead of doing as follows
and then concatenating it.
const string EMP_COLS=
EMPLOYEE.EMPID + "," +
EMPLOYEE.FNAME + "," +
EMPLOYEE.LNAME + "," +
EMPLOYEE.DEPTID;
const string EMP_Values=
EMPLOYEE.EMPID + ":" +
EMPLOYEE.FNAME + ":" +
EMPLOYEE.LNAME + ":" +
EMPLOYEE.DEPTID;
You could try something like this:
StringBuilder sb = new StringBuilder();
var fields = typeof(Employee).GetFields();
for (int i = 0; i < fields.Length; ++i)
{
sb.Append(fields[i].GetValue(new Employee()));
if (i < fields.Length - 1)
{
sb.Append(',');
}
}
string result = sb.ToString();
// The above will be "EMP_ID,FIRST_NAME,LAST_NAME,DEPT_ID"
Edit: Note that above I'm assuming you've got using directives for both System.Reflection and System.Text.
If the struct held readonly properties rather than public consts you could do it with Reflection. You could call Type.GetProperties, loop through them all and call them to get out the values and insert the values into a List<string> and then join them with string.Join(", ", myList); or something.
You'd then get the first part of the string as EMP_ID, FIRST_NAME, LAST_NAME, DEPT_ID and you'd need to make a copy of that and add the :s as needed and you'd have both parts.
you can use the string.Format(string format, object[] arg) Method as follows:
string query = string.Format("INSERT INTO EMP({0},{1},{2},{3}) VALUES(:{0},:{1},:{2},:{3})",
Employee.EMPID,
Employee.FNAME,
Employee.LNAME,
Employee.DEPTID);
Hope that helps.
You will need some kind of mapping dictionary, like here, or you could just use some ORM tool to do the mapping for you.
string[] values = new[] {
"EMP_ID",
"FIRST_NAME",
"LAST_NAME",
"DEPT_ID",
};
var columns = string.Join(",", values);
var parameters = ":" + string.Join(",:", values);
var sql = string.Format("INSERT INTO EMP({0}) VALUES({1})",
columns,
parameters);
string[] cols = typeof(Employee).GetFields()
.Select(f => f.GetValue(null).ToString()).ToArray();
Console.WriteLine(string.Format(
"INSERT INTO EMP({0}) VALUES(:{1})",
string.Join(",", cols),
string.Join(",:", cols)));

Categories