Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
i have below code where string dont get concatenated
string postCode = "1245";
string city = "Stockholm";
string postCodeAndCity = postCode ?? " " + " " + city ?? " ";
I get output as 1245. Not sure why it excludes city.
But this line works
string.Concat(postCode??" ", " ", city?? " ");
so why the first approach dont work?
The ?? operator associates like this:
string postCodeAndCity = postCode ?? (" " + " " + city ?? (" "));
So if postCode is not null, it just takes postCode. If postCode is null, then it takes (" " + " " + city ?? (" ")).
You can see this from the precedence table, where ?? has lower precedence than +. Therefore + binds more tightly than ??, i.e. a ?? b + c binds as a ?? (b + c), not as (a ?? b) + c.
However, in:
string.Concat(postCode??" ", " ", city?? " ");
The commas of course have higher precedence than the ??. The equivalent using + would be:
(postCode ?? " ") + " " + (city ?? " ");
I suspect what you might want to do is:
If both postCode and city are not null, take both with a space between them.
If one is null but the other isn't, take the non-null one.
If both are null, take an empty string.
You can write this long-hand:
if (postCode != null)
{
if (city != null)
return postCode + " " + city;
else
return city;
}
else
{
if (postCode != null)
return postCode;
else
return "";
}
You can write this a bit shorter (although slightly more expensively) with:
string.Join(" ", new[] { postCode, city }.Where(x => x != null));
You should use string interpolation for this:
var output = $"{postCode} {city}"
For more information see:
https://learn.microsoft.com/de-de/dotnet/csharp/language-reference/tokens/interpolated
Related
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + txtFirstName.Text[0] + txtMiddle.Text + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
I'm trying to get 1 character white space inbetween cboTitle.Text, txtFirname.Text, txtMiddle.Text, and txtLastName, but they all output the information together, but I want them spaced evenly. what do I need to do? thanks in advance.
I'm going to post some other code thats below the one above in my project, just in case it might be relevant.
string AssembleText(string Title, string FirstName, string MiddleInitial, string LastName, string AddressLines, string City )
{
string Result = "";
Result += Title + " ";
Result += FirstName.Substring(0, 2) + " ";
// Only append middle initial if it is entered
if (MiddleInitial != "")
{
Result += MiddleInitial + " ";
}
Result += LastName + "\r\n";
// Only append items from the multiline address box
// if they are entered
if ( AddressLines != "")
{
Result += AddressLines + "\r\n";
}
//if (AddressLines.Length > 0 && AddressLines.ToString() != "")
//{
// Result += AddressLines + "\r\n";
//}
Result += City;
return Result;
}
}
}
If you just want a space between those specific fields in btnAssemble_Click, you can just insert them like this:
string myStr = foo + " " + bar + " " + baz;
So your first function would be modified to read:
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " + txtMiddle.Text + " " + txtLastName.Text + "\r\n" + txtStreet.Text + "\r\n" + cboCity.Text);
}
A few other comments:
It's not clear to me what the AssembleText() function you posted has to do with this. I am confused though, as I see a few lines appending spaces at the end just like I mentioned above.
Using the String.Format() function may make this code easier to read and maintain.
Using Environment.NewLine instead of "\r\n" will make the string contain the newline character defined for that specific environment.
Using a StringBuilder object may be faster over concatenation when building strings inside of a loop (which may not apply here).
Using String.format() should feet the bill. It also make your code easy to read.
txt.assembled.text = String.Format("{0} {1} {2} {3}",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text
);
It would be like this
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " +txtMiddle.Text + " " + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
It seems that you want String.Join; whenever you want to combine strings with a delimiter, say, " " (space) all you need is to put
String combined = String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text);
Complete implementation (joining by space and new line) could be
txtAssembled.Text = String.Join(Environment.NewLine,
String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text),
txtStreet.Text,
cboCity.Text);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the below code but I know it doesn't work as when I try declaring it, my code says it's not defined but I don't know how to write it.
I no I need to declare is before my IF statement but not sure how. Below is what I have but I know its wrong as I keep saying
if (Session["Step01Tel"] != "")
{
var ContactDetails = Step01TelLabel.Text + " " + Session["Step01Tel"].ToString();
}
else if (Session["Step01Email"] != "")
{
var ContactDetails = Step01EmailLabel.Text + " " + Session["Step01Email"].ToString();
}
Then I'm after something like the below in my code to call it as its for the body of my email that my site sends.
msg.Body = ContactDetails.Tostring()
The reason I'm after this is that if the Tel or Email field is empty then I don't want the Tel/Email label to be displayed in the email and you can not us an If inside an email body.
The below shows how I initially had it but as I said this displayed the field label with no value.
////NEED TO ONLY DISPLAY IF VALUE IS PRESENT
// Step01TelLabel.Text + " " + Session["Step01Tel"].ToString()
// + Environment.NewLine.ToString() +
// Step01EmailLabel.Text + " " + Session["Step01Email"].ToString()
// + Environment.NewLine.ToString() +
////
Try this
var ContactDetails = string.Empty;
if (Session["Step01Tel"] != "")
{
ContactDetails = Step01TelLabel.Text + " " + Session["Step01Tel"].ToString();
}
else if (Session["Step01Email"] != "")
{
ContactDetails = Step01EmailLabel.Text + " " + Session["Step01Email"].ToString();
}
Here is the offending code. I haven't done much string manipulation yet, and am currently having issues.
if (orderid != orderlist[orderlist.Count - 1])
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
}
else
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "success", response2);
}
Console.WriteLine("Response 2 is: " + response2);
logger.Log("Writing " + writepath + filename);
File.WriteAllText(writepath + filename, response2);
}
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
Console.WriteLine("String a is: " + a + "String b is: " + b + "String c is: " + c);
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
I am having issues extracting a substring, as the beginning and ending strings are the same, and therefore it is unable to differentiate the strings from each other.
Here is the main issue:
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
Is there a way I can add a check if the orderid for the ending string differs from the starting string orderid? Thanks for any help!
I was working with code that was already set to scan rather than parse JSON in the optimal fashion.
I utilized this regex to remove orderid before each number as to not cause scanner length exceptions. I also overloaded string.IndexOf as mentioned by juharr.
var regex = new Regex(Regex.Escape("orderid")); //replace first occurrence of orderid
response2 = regex.Replace(response2, "", parsecount-1);
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
logger.Log("String a is: " + a + "String b is: " + b + "String c is: " + c);
var offset = c.IndexOf(b);
//lastcheck will return 0 if it's last element in orderlist, because ending string differs for last
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b, offset + lastcheck) - c.IndexOf(a) - a.Length));
}
I had the following:
string Name = name.First + " " + name.Last;
This returns Tom Jones just fine.
In case name.First may be null or name.Last may be null, I have the following:
string SpeakerName = name.First ?? string.Empty + " " + name.Last ?? string.Empty;
What is strange is that it only returns Tom. Why is this and how can I fix it such that if null it defaults to empty string for either first or last name?
Because of the relative precedence of the ?? and + operators. Try this:
string SpeakerName = (name.First ?? "") + " " + (name.Last ?? "");
Your original example is evaluating as if it was:
string SpeakerName = name.First ?? ("" + " " + (name.Last ?? ""));
Also, read Jon's answer here: What is the operator precedence of C# null-coalescing (??) operator?
As he suggests there, this should work as well:
string SpeakerName = name.First + " " + name.Last;
Because that compiles to #L.B.'s answer below, minus the trim:
string SpeakerName = String.Format("{0} {1}", name.First, name.Last)
EDIT:
You also asked that first and last both == null makes the result an empty string. Generally, this is solved by calling .Trim() on the result, but that isn't exactly equivalent. For instance, you may for some reason want leading or trailing spaces if the names are not null, e.g. " Fred" + "Astair " => " Fred Astair ". We all assumed that you would want to trim these out. If you don't, then I'd suggest using a conditional:
string SpeakerName = name.First + " " + name.Last;
SpeakerName = SpeakerName == " " ? String.Empty : SpeakerName;
If you never want the leading or trailing spaces, just add a .Trim() as #L.B. did
string SpeakerName = String.Format("{0} {1}", name.First, name.Last).Trim();
string SpeakerName = name.First != null && name.Last != null
? string.Format("{0} {1}", name.First, name.Last)
: string.Empty;
string fullName = (name.First + " " + name.Last).Trim();
This works for either or both being null and will not return a string with leading, trailing, or only spaces.
Here's what I've got, I need to keep the console from returning additional commas on the main program, so I probably need to rewrite string e. Month, description etc. should still have commas, but if something like "note" is absent, those additional commas would be gone.
public override string ToString()
{
string e = description + ", " + month + day + year + ", " + amount.ToString("C") + ", ";
e = e + paymentMethod + ", " + trip + ", " + note;
return e;
}
You can try something like this, to filter out empty elements:
public override string ToString()
{
string[] elements = new string[] { description,
String.Concat(month, day, year),
amount.ToString("C"), paymentMethod, trip, note };
return String.Join(", ", elements.Where(s => !String.IsNullOrWhiteSpace(s)));
}
A little more verbose option, but also less confusing and C# 2 compatible:
private static void AddIfNotNull(List<string> elements, string value)
{
if (!String.IsNullOrEmpty(value))
elements.Add(value);
}
public override string ToString()
{
List<string> elements = new List<string>();
AddIfNotNull(elements, description);
elements.Add(String.Concat(month, day, year));
elements.Add(amount.ToString("C"));
AddIfNotNull(elements, paymentMethod);
AddIfNotNull(elements, trip);
AddIfNotNull(elements, note);
return String.Join(", ", elements.ToArray());
}
You could rewrite ToString like this, is that what you want?
public override string ToString()
{
string e = description + " " + month + day + year + " " +
amount.ToString("C") + " ";
e = e + paymentMethod + " " + trip + " " + note;
return e;
}