Cannot trim from the end of string - c#

When the following is executed:
foreach (String fromList in columns)
{
query += "`" + fromList + "`,";
}
query.TrimEnd(',');
The comma is not trimmed from the string.
What am I doing wrong?

TrimEnd returns the new string. You need:
query = query.TrimEnd(',');

Strings are immutable, so you need to store the return value from TrimEnd.
query = query.TrimEnd(',');
Though there is an easier way to do this:
var query = String.Join(",", columns.Select(fromList => String.Format("`{0}`", fromList)));

TrumEnd returns a string. Are you assigning it to a variable ?

Use the below example:
var trimmed = query.TrimEnd(',');
Console.WriteLine(trimmed);

It should be
foreach (String fromList in columns)
{
query += "`" + fromList + "`,";
}
query = query.TrimEnd(',');

Strings are immutable. If you want the result after applying TrimEnd, you have to assign that result to a variable:
foreach (String fromList in columns)
{
query += "`" + fromList + "`,";
}
query = query.TrimEnd(',');
Here I've assigned it back to itself.
Of course, better would be something like:
query = String.Join(",",fromList.Select(a=>"`" + a + "`"));
instead of the loop + edit.

Related

Change special chars in string

I am using c# and in code from appsettings.json I take strings and convert them if special chars exists. this is my code
int? a = applicationRequestViewModel.GetApplicantIndex();
int? g = applicationRequestViewModel.GetGurantorIndex();
foreach (var keys in _options.Value.RegisterParamKeys)
{
string value = keys.Split(";")[0];
string name = keys.Split(";")[1];
string key = value.Split(":")[typeOfApplicant];
key = Regex.Replace(key, #"[^\[a\]]", "[" + a + "]");
key = Regex.Replace(key, #"[^\[g\]]", "[" + g + "]");
var registrationProperty = new RegistrationProperty() { };
registrationProperty.Name = name;
registrationProperty.Value = (string)rss.SelectToken(key);
listOfRegistrationProperty.Add(registrationProperty);
}
from appsettings.json I took below strings
"RegisterBatchParams": [
"applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber;applicationNumber",
"applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType;applicantType",
"applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment;customerSegment",
"applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText;applicationStatus",
"applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName;customerName"
],
for the last string I want to change "applicants[a]" to with index number but it doesn't convert as expected how can I convert correctly?
As expected result
applicationRequestViewModel.applicants[0].businessPartner.person.firstName
but given result
a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0]a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0][0]
Instead of #"[^\[a\]]" use #"\[a\]".
But you don't even need regex for this. Simple string.Replace will do the job just as well.
Or, you can try this regex and replace only char inside of parentheses.
[a](?=[]])

Removing the last two or multiple words from a string in c#

I have string likely
select 'abc','xyz','123' Union all select 'def','wer','456' Union all
the string is generated by loop e.g.
foreach(var item in obj)
{
" SELECT'" + item.a + "'," + item.b + ," + item.c + "UNION ALL";
}
Now i want to remove the "Union all" written in the last of the string.How can i do this is single OR using regex in C# .IndexOf wont work as i have multiple "Union all" in my string .
As far as I can see, you are trying to build finalQuery from several selects; you can do it with a help of Join:
string[] selects = new string[] {
"select 'abc','xyz','123'",
"select 'def','pqr','456'",
};
// select 'abc','xyz','123' Union all select 'def','pqr','456'
string finalQuery = string.Join(" Union all ", selects);
If you, however, want to remove the very last Union all if it is, you can test the string with EndsWith:
string finalQuery = myString.EndsWith("Union all")
? myString.Substring(0, myString.Length - "Union all".Length)
: myString;
Edit: If you generate your selects in a loop (see comments below), you can try extracting method turning loop into IEnumerable<String>:
private IEnumerable<string> MySelects() {
foreach(var item in obj) {
// Some Logic Here...
// When you are ready to create a select just "yield return" it and keep looping
yield return $" SELECT '{item.a}', '{item.b}', '{item.c}'";
// Some Other Logic Here...
}
}
and then again Join:
string finalQuery = string.Join(" Union all ", MySelects());
Finally, if you want to stick to loop (for whatever reason), add if:
StringBuilder sb = new StringBuilder();
foreach(var item in obj) {
// if we have a query, next one should be add via "UNION ALL"
if (sb.Length > 0)
sb.Append(" UNION ALL ");
sb.Append($"SELECT '{item.a}', '{item.b}', '{item.c}'");
}
string finalQuery = sb.ToString();
You can combine string.Join and LINQ Skip:
string input = "select 'abc','xyz','123' Union all select 'def','wer','456' Union all";
string result = string.Join(" ", input.Split(' ').Reverse().Skip(2).Reverse());
DEMO HERE
I would start with somelink like this. In case your replacement gets more complicated you can start using regular expressions.
var toRemove = "Union all";
if (yourString.EndWith(toRemove ))
{
yourString = yourString.SubString(0, yourString.Length - toRemove.Length).Trim();
}
P.S. Get the toRemove string from some logical location and don't use it in your procedure like this to avoid using magic values..
You can use this as a function;
var toRemove = "Union all";
if (string.IsNullOrWhiteSpace(yourString))
return;
var pos = yourString.LastIndexOf(stringToFind);
if (pos < 0) return;
string newString = yourString.Remove(pos, yourString.Length);
return newString;

How to comma-separate a set of strings without the final comma

int rowPosition = 0;
string WorkerName = "";
DataTable dtAllotedManpower = new DataTable();
dtAllotedManpower.Columns.Add("WorkerName");
foreach (GridViewRow row in GridViewTotalManpower.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
DataRow drAllotedManpower = dtAllotedManpower.NewRow();
CheckBox chkChild = (CheckBox)GridViewTotalManpower.Rows[rowPosition].FindControl("chkChild");
if (chkChild.Checked == true)
{
WorkerName = Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()) + "," + WorkerName;
}
rowPosition++;
}
hidfWorker.Value = WorkerName;
I have Written the following piece of code. My hidden field values are coming like this
"HARSH,RIMA,"
But i want the value "HARSH,RIMA" (without ',' after the last word). how to construct the code for that ? . there will be no 'comma' after last word .
Add them to a collection then use string.Join:
var list = new List<string>();
foreach (GridViewRow row in GridViewTotalManpower.Rows) {
// ...other code here...
list.Add(Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()));
}
hidfWorker.Value = string.Join(", ", list);
You can use string.TrimEnd()
hidfWorker.Value = WorkerName.TrimEnd(',');
This will remove the last comma from the string.
you can use the substring method
hidfWorker.Value=WorkerName.Substring(0,WorkerName.Length-1);
Use StringBuilder instead of string if you are frequently changing the string like in loops, because when you use string it will create new string object every time you changes it,
StringBuilder workerName = new StringBuilder();
And in your loop
workerName.Append(Convert.ToString(GridViewTotalManpower.DataKeys[rowPosition]["WorkerName"].ToString()) + ",");
Then trim last ',' character using TrimEnd method
hidfWorker.Value = workerName.ToString().TrimEnd(',');
Hope this helps.

Passing string value after apply split function in asp.net c#

I have fail to pass the string value to label or text box after split function. So my question is how to store the string value in label after applying the split function.
string strData2 = "samsung,apple,htc";
char[] separator2 = new char[] { ',' };
string[] strSplitArr = strData2.Split(separator2);
foreach (string arrStr in strSplitArr)
{
Response.Write(arrStr + "<br/>");
}
(e.g. label.text = ""+ the split string value )
Thanks
You can use String.Join:
label.Text = String.Join("," , strSplitArr);
Concatenates all the elements of a string array, using the specified
separator between each element.
Try:
label.text = label.text + arrStr;
to list one after other with break, do
label.text = label.text + arrStr + "</br>";
Do you want to join these in one string again? Use String.Join:
label.Text += String.Join(' ',strSplitArr);
source: http://msdn.microsoft.com/pl-pl/library/57a79xd0.aspx

C# replace part of string but only exact matches possible?

I have a string beginString = "apple|fruitsapple|turnip";
What I want to do is replace just apple with mango, not fruitsapple.
string fixedString = beginString.Replace("apple","mango"); This doesn't work because it replaces both apple and fruitsapple.
Any ideas?
beginString = "|" + beginString + "|";
fixedString = beginString.Replace("|apple|","|mango|");
This cannot be done in the way you have said since it will consider the entire string to be a string. You can do the split by | as you have used or else have the strings in a list and use equals and then replace it.
String[] words = beginString.Split("|");
now do the replace on words. works for any scenario.
The variation on other answers in LINQ style:
string fixedString = string.Join("|",
beginString
.Split('|')
.Select(s => s != "apple" ? s : "mango"));
Closest I can get. Was gonna suggest regular expression, but that won't always work as you want. You have to split the string first and then remake it.
string searchString = "apple";
string newString = "mango";
string beginString = "apple|fruitsapple|turnip";
string[] array = beginString.Split('|');
foreach (var item in array)
{
if (item == searchString)
item.Replace(searchString, newString);
}
string recreated = "";
new List<string>(array).ForEach(e => recreated += e + "|");
recreated.TrimEnd('|');
string newstr = Regex.Replace("apple|fruitsapple|turnip", #"\bapple\b", "mango");

Categories

Resources