Getting first name on name string with substring fails [C#] - c#

So i have this piece of code:
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
lets suppose the name is "Phiter Fernandes", ok it will say:
Welcome, Phiter!
But if the name is just "Phiter" it will stop and not run the rest of the code.
Obviously is because there are no spaces for the substring method to retrieve the first name.
But i don't want it to skip the rest of the code, i want it to work even if there is no space.
I tried using the try catch, just like this:
try
{
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
}
catch
{
MessageBox.Show("Welcome," + name + "!");
}
It works, but there is an annoying sound when the code runs the catch.
Is there any other way around this? A different way of getting the first name, perhaps?

Try splitting the string wherever there is a space, and selecting the first element, which will always be the first name.
MessageBox.Show("Welcome," + name.Split(' ')[0] + "!");

You can try more than one options.
Replace usign Regex.
string input = "Your string " + "whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
check if space exists.
if(name.Contains(" "))
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
trim spaces
string fullName = name;
var names = fullName.Split(' ');
string firstName = names[0];
MessageBox.Show("Welcome," + firstName + "!");
Let me know which one did you use!

Related

Environment.NewLine Does Not Put Each entry On New Row

I have the following code which is to display an address but it does not seem to put each address row on a new line and cant figure out why
var selectedOrigoScheme = origoCedingSchemes.Where(x => x.complyingFundId.ToString() == SelectedSchemeId).ToList();
string origoName = !String.IsNullOrEmpty(selectedOrigoScheme[0].origoName) ? selectedOrigoScheme[0].origoName + Environment.NewLine : "";
string propertyName = !String.IsNullOrEmpty(selectedOrigoScheme[0].propertyName) ? selectedOrigoScheme[0].propertyName + Environment.NewLine : "";
string streetNumber = !String.IsNullOrEmpty(selectedOrigoScheme[0].streetNumber) ? selectedOrigoScheme[0].streetNumber + Environment.NewLine : "";
string street = !String.IsNullOrEmpty(selectedOrigoScheme[0].street) ? selectedOrigoScheme[0].street + Environment.NewLine : "";
string street2 = !String.IsNullOrEmpty(selectedOrigoScheme[0].street2) ? selectedOrigoScheme[0].street2 + Environment.NewLine : "";
string suburb = !String.IsNullOrEmpty(selectedOrigoScheme[0].suburb) ? selectedOrigoScheme[0].suburb + Environment.NewLine : "";
string district = !String.IsNullOrEmpty(selectedOrigoScheme[0].district) ? selectedOrigoScheme[0].district + Environment.NewLine : "";
string postcode = !String.IsNullOrEmpty(selectedOrigoScheme[0].postcode) ? selectedOrigoScheme[0].postcode + Environment.NewLine : "";
string Origoaddress = origoName + propertyName + streetNumber + street + street2 + suburb + district + postcode;
viewData["Origoaddress"] = Origoaddress;
When I debug I get the following result:
Aviva\r\nNorwich Business Capture Centre\r\nPO Box 520\r\nNorwich\r\nNR1 3WG \r\n
If I look at the result in text visualizer it displays correctly:
Aviva
Norwich Business Capture Centre
PO Box 520
Norwich
NR1 3WG
But if I look at it using HTML visualizer it displays as:
Aviva Norwich Business Capture Centre PO Box 520 Norwich NR1 3WG
Which is how its showing in my address field on the website.
What am I doing wrong as I cant see the issue.
HTML
<%=Html.TextBox("Origoaddress", ViewData["Origoaddress"].ToString())%>
Html ignores white spaces so is ignoring the line breaks you have added. If you were working in pure html you'd need to use < br>. Html.TextBox only supports single line strings so doesn't add line breaks that Html will understand.
In order to use multiple lines you will probably need to use TextArea. See creating multiline textbox using Html.Helper function
for further details.

C# Creating white space lines between assembled .text

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);

C# passing quotes in string

I am trying to pass quotes in string. I am having a hard time formulating the code.
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = "Set-UserPhoto ";
format += "" + user + "";
format += " -PictureData ([System.IO.File]::ReadAllBytes(";
format += "" + path + #"";
format += ")";
The user and path are variables that needs to be inside single quotes for the AD Command. command. What I have isn't working.
User \" for " symbol or \' for '
format += "\"" + user + "\"";
First of all , use string.format for such tasks. Second you have to escape quotes ( but you dont need to escape single quotes).
Double quotes can be escaped by double quote or by backslash based on type of string literal you are using:
var s = #"something "" somethin else "; // double double quote here
var s2 = "something \" somethin else ";
Now, using string.format, your code will turn into:
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format("Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(\"{1}\")", user, path);
or
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format(#"Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(""{1}"")", user, path);
string format = "Set-UserPhoto "; format += "'" + user + "'"; format += " -PictureData ([System.IO.File]::ReadAllBytes("; format += "'" + path + #"'"; format += ")";
I would suggest using string interpolation within a here-string as follows, this will prevent you from having to use string concatenation and escaping.
$format = #"
Set-UserPhoto " + user + " -PictureData ([System.IO.File]::ReadAllBytes(" + path + ")"
"#

Find number pattern in string and remove it

I need to remove a pattern from a string, I think regex could do the job, but I'm having trouble solving this.
The pattern must be in the end of the string.
string fileName = "File (123)";
string pattern = " (0)";
string cleanName = PatternRemover(fileName, pattern);
//Should result in: cleanName == "File"
Edit:
Ok, here is the code that I'm using now after your answers:
public static string GetNextFilePath2(string fullPath, ref uint id, string idFormat)
{
string dir = Path.GetDirectoryName(fullPath);
string ext = Path.GetExtension(fullPath);
string fileNameNoExt = Path.GetFileNameWithoutExtension(fullPath);
if (ext.Length > 0 && ext[0] != '.')
ext = "." + ext;
string baseName = Regex.Replace(fileNameNoExt, #"\s\(\d+\)", "");
string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
string path = Path.Combine(dir, fileName);
while (File.Exists(path))
{
id++;
fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
path = Path.Combine(dir, fileName);
}
return path;
}
It works, but:
It always start to count from id, I think it may be better to start
from the file name number.
I was hopping to use something like "(0)" as a method parameter that would indicate the pattern to be removed and also the "(" would be parametrized. I'm doing it "manually" now on this line: string fileName = baseName + " (" + id.ToString(idFormat) + ")" + ext;
You can do that without REGEX like:
string newFileName = new String(fileName
.Where(r => !char.IsDigit(r)
&& r != '('
&& r != ')'
&& r != ' ').ToArray());
This would give you File.jpg
If you only want to get the file name then you can use:
string fileNameWithoutPath = Path.GetFileNameWithoutExtension(newFileName);
// it would give you `File`
Using regex:
var subject = "File (123).jpg";
var fileNameWithExtension = Regex.Replace(subject,#"\s*\(\d+\)","");
var fileNameWithoutPath = Path.GetFileNameWithoutExtension(fileNameWithExtension);
And thanks for #habib, I'd not have come with Path.GetFileNameWithoutExtension in this for stripping the extension.
You could use:
\s\(\d+\)\.jpg
assuming you do actually want the extension removed and the extension is always ".jpg". Otherwise:
\s\(\d+\)
Looks for a set of digits in brackets proceeded by a space.

c# null string?

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.

Categories