How do you grab the first letter in a string? - c#

I'm working with an entity (Employee) that has 3 fields: FirstName, LastName, & Login
I want to grab the lastname and the first letter of the firstname field and write this to the login field. How do I grab the first letter of the firstname?
Thanks for any help.

Just as simple as:
if (!string.IsNullOrEmpty(Employee.FirstName))
{
string firstLetter = Employee.FirstName.SubString(0, 1);
}
With that you get the first letter as a string and with this the character:
if (!string.IsNullOrEmpty(Employee.FirstName))
{
char firstLetter = Employee.FirstName[0];
}

To get the first character (not necessarily a letter) use an index into the string:
char c = employee.FirstName[0];
You may also want to first check that the string is non-null and non-empty and strip leading whitespace, and that the first character is actually a letter:
if (employee != null && employee.FirstName != null) {
string name = employee.FirstName.TrimStart();
if (name.Length > 0) {
char firstChar = name[0];
if (char.IsLetter(firstChar)) {
employee.Login = firstChar.ToString();
}
}
}

char firstCharOfFirstName = someEmployee.FirstName[0];
If the FirstName field can have leading whitespace you can do:
char firstCharOfFirstName = someEmployee.FirstName.Trim()[0];
(As the other answers mention it's good to check for empty string and null string)

If the first name might be empty, you would have to check that when getting the first letter:
FirstName.Substring(0, Math.Min(FirstName.Length, 1))
This will give you an empty string if the FirstName string is empty, otherwise the first character as a string, so that you can concatenate it with the last name.

Bear in mind, SubString() or FirstName[0] will throw a ArgumentOutOfRangeException or IndexOutOfRangeException if
FirstName == string.Empty
So, this code will at least avoid exception:
if(str2 != null)
{
char result = (str2.Length > 0)
? str2[0]
: (char)0;
}
Don't forget this code will return a false result if the string is empty!

Related

How to do I cut off a certain part a String?

I have a big String in my program.
For Example:
String Newspaper = "...Blablabla... What do you like?...Blablabla... ";
Now I want to cut out the "What do you like?" an write it to a new String. But the problem is that the "Blablabla" is everytime something diffrent. Whit "cut out" I mean that you submit a start and a end word and all the things wrote between these lines should be in the new string. Because the sentence "What do you like?" changes sometimes except the start word "What" and the end word "like?"
Thanks for every responds
You can write the following method:
public static string CutOut(string s, string start, string end)
{
int startIndex = s.IndexOf(start);
if (startIndex == -1) {
return null;
}
int endIndex = s.IndexOf(end, startIndex);
if (endIndex == -1) {
return null;
}
return s.Substring(startIndex, endIndex - startIndex + end.Length);
}
It returns null if either the start or end pattern is not found. Only end patterns that follow the start pattern are searched for.
If you are working with C# 8+ and .NET Core 3.0+, you can also replace the last line with
return s[startIndex..(endIndex + end.Length)];
Test:
string input = "...Blablabla... What do you like?...Blablabla... ";
Console.WriteLine(CutOut(input, "What ", " like?"));
prints:
What do you like?
If you are happy with Regex, you can also write:
public static string CutOutRegex(string s, string start, string end)
{
Match match = Regex.Match(s, $#"\b{Regex.Escape(start)}.*{Regex.Escape(end)}");
if (match.Success) {
return match.Value;
}
return null;
}
The \b ensures that the start pattern is only found at the beginning of a word. You can drop it if you want. Also, if the end pattern occurs more than once, the result will include all of them unlike the first example with IndexOf which will only include the first one.
You have to do a substring, like the example below. See source for more information on substrings.
// A long string
string bio = "Mahesh Chand is a founder of C# Corner. Mahesh is also an
author, speaker, and software architect. Mahesh founded C# Corner in
2000.";
// Get first 12 characters substring from a string
string authorName = bio.Substring(0, 12);
Console.WriteLine(authorName);
In this case I would do it like this, cut the first part and then the second and concatenate with the fixed words using them as a parameter for cutting.
public string CutPhrase(string phrase)
{
var fst = "What";
var snd = "like?";
string[] cut1 = phrase.Split(new[] { fst }, StringSplitOptions.None);
string[] cut2 = cut1[1].Split(new[] { snd }, StringSplitOptions.None);
var rst = $"{fst} {cut2[0]} {snd}";
return rst;
}

LINQ: Null checking in string.Format()

I have a requirement to get the first letter of the first, middle and last names. It is working if each of the fields contain value. But the middle name is nullable field. So i'm getting error if the value of middle name is null.
(from P in this._dbContext.Person
where P.PersonIndex == personIndex
select new PersonInitialsDTO
{
PersonIndex = P.PersonIndex,
PersonInitials = string.Format("{0}{1}{2}", P.FirstName.ToUpper().First(), P.MiddleName.ToUpper().First(), P.LastName.ToUpper().First())
}).FirstOrDefault();
use ? to see if the value is null before executing next methods.
string.Format("{0}{1}{2}", P.FirstName.ToUpper().First(), P.MiddleName?.ToUpper().First(), P.LastName.ToUpper().First())
P.MiddleName?.ToUpper().First() -> If P.MiddleName is null, dont do ToUpper() or any other methods afterwards.
Example of use of ?. in string.format statement.
Pers person = new Pers()
{
First = "First",
Last = "Last"
};
Console.WriteLine(string.Format("{0}{1}{2}", person.First.First(), person.Middle?.ToUpper().First(), person.Last.First()));
// Prints
FL
Requirement: get the first letter of the first, middle and last names.
Well, apparently this requirement is not complete: if one of these names is null or empty, there is no first letter.
Furthermore: if I look at the code, you don't want the first letter, you want a string that contains the first letter.
And why uppercase the complete string if you will only use the first character?
So let's change it slightly:
Requirement: Given three strings: first, middle and last, get me the string that contains the uppercase values of the first character of each of these strings, or String.Empty if the string is null or empty.
"Vincent" "van" "Gogh" => "VVG"
"rembrandt" "van" "rijn" => "RVR"
"Piet" "Mondriaan" => "PM"
From each of these three strings,
Check if if it is null, if so, use Enumerable.Empty<char>
Create a sequence that contains only the first character of the string. So if the string was null or empty, this first character will be an empty sequence of character).
Concatenate these three sequences.
Result: a sequence of characters that contains only the first character of each of these strings, or no character at all if the string was null or empty.
In baby steps, I'll write the type in front, so you can see what happens.
string first = ...
string middle = ...
string last = ...
IEnumerable<char> firstChars = first?.Take(1) ?? Enumerable.Empty<char>(),
IEnumerable<char> midChars = middle?.Take(1) ?? Enumerable.Empty<char>(),
IEnumerable<char> lastChars = last?.Take(1) ?? Enumerable.Empty<char>(),
IEnumerable<char> chars = firstChars.Concat(midChars).Concat(lastChars);
So from our original input examples we have:
Vincent Van Gogh: {'V', 'V', 'G'}
rembrandt van rijn: {'r', 'v', 'r'}
Piet Mondriaan {'p', 'm'}
So all we have to do is to convert them to uppercase and convert to a string:
IEnumerable uppercaseChars = chars.Select(c => Char.ToUpper(c));
Note: until know the query is not executed! I only used methods that use deferred execution!
string result = new string(uppercaseChars.ToArray());
Of course you can write this in one big LINQ statement. I'm not sure if that would improve readability. It won't have any effect on performance.
I tried with below. Now it's working
(from P in this._dbContext.Person
where P.PersonIndex == personIndex
select new PersonInitialsDTO
{
PersonIndex = P.PersonIndex,
PersonInitials = (P.MiddleName == "")
? string.Format("{0}{1}", P.FirstName.ToUpper().First(),
P.LastName.ToUpper().First())
: string.Format("{0}{1}{2}", P.FirstName.ToUpper().First(),
P.MiddleName.ToUpper().First(), P.LastName.ToUpper().First())
}).FirstOrDefault();

How to replace empty position with a 0 value when converting string to array in C#?

Update: July 26, 2017
I have a string inside which the values are comma separated. However for some cases it is coming double comma ,, at in a consecutive way. But when I am using using string.split(',') it's returning me a array which doesn't have a value on that index. For example
string str = "12,3,5,,6,54,127,8,,0,98,"
It's breaking down the the array this way
str2[0] = 12
str2[1] = 3
str2[2] = 5
str2[3] = ""
str2[4] = 6
str2[5] = 54
str2[6] = 127
str2[7] = 8
str2[8] = ""
str2[9] = 0
str2[10] = 98
str2[11] = ""
Look here I am getting the array with one or more empty value. So I want to put a 0 in each empty position when I am splitting the string. Here I have found something to skip the empty values
str .Split(',', StringSplitOptions.RemoveEmptyEntries)
However I did not found such a solution put a default value at empty index. I have gone through these previous Questions Q1, Q2, But these are not effective for mine. I am using C# for web application in .Net framework
Try the below code:
You can able to use IEnumerable extension method (Select) of String object.
string str = "12,3,5,,6,54,127,8,,0,98";
var strVal = str.Split(',').Select(s => string.IsNullOrWhiteSpace(s) ? "0" : s);
Use the following code to replace empty string to zero
string str = "12,3,5,,6,54,127,8,,0,98";
var a= str.Split(',').Select(x=>string.IsNullOrEmpty(x)?"0":x);
While all the suggested solutions work perfectly, they are all iterating twice your input (once for the string split, once for the string replace or regex, once for the array replace).
Here is a solution iterating only once the input:
var input = "12,3,5,,6,54,127,8,,0,98";
var result = new List<int>();
var currentNumeric = string.Empty;
foreach(char c in input)
{
if(c == ',' && String.IsNullOrWhiteSpace(currentNumeric))
{
result.Add(0);
}
else if(c == ',')
{
result.Add(int.Parse(currentNumeric));
currentNumeric = string.Empty;
}
else
{
currentNumeric += c;
}
}
if(!String.IsNullOrWhiteSpace(currentNumeric))
{
result.Add(int.Parse(currentNumeric));
}
else if(input.EndsWith(","))
{
result.Add(0);
}
You can run your string through regex to put zeros into it before going into Split:
Regex.Replace(str, "(?<=(^|,))(?=(,|$))", "0").Split(',')
The regex will insert zeros into the original string in spots when two commas are next to each other, or when a comma is detected at the beginning or at the end of the string (demo).

Remove last specific character in a string c#

I use WinForms c#.I have string value like below,
string Something = "1,5,12,34,";
I need to remove last comma in a string. So How can i delete it ?
Try string.TrimEnd():
Something = Something.TrimEnd(',');
King King's answer is of course correct, and Tim Schmelter's comment is also good suggestion in your case.
But if you really want to remove the last comma in a string, you should find the index of the last comma and remove it like this:
string s = "1,5,12,34,12345";
int index = s.LastIndexOf(',');
Console.WriteLine(s.Remove(index, 1));
Output will be:
1,5,12,3412345
Here is a demonstration.
It is unlikely that you want this way but I want to point it out. And remember, the String.Remove method doesn't remove any characters in the original string, it returns new string.
Try string.Remove();
string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);
The TrimEnd method takes an input character array and not a string.
The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.
static string TrimTrailingChars(string value)
{
int removeLength = 0;
for (int i = value.Length - 1; i >= 0; i--)
{
char let = value[i];
if (let == '?' || let == '!' || let == '.')
{
removeLength++;
}
else
{
break;
}
}
if (removeLength > 0)
{
return value.Substring(0, value.Length - removeLength);
}
return value;
}
Dim psValue As String = "1,5,12,34,123,12"
psValue = psValue.Substring(0, psValue.LastIndexOf(","))
output:
1,5,12,34,123
Try below
Something..TrimEnd(",".ToCharArray());
Or you can convert it into Char Array first by:
string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];
Now you have each character indexed:
SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','
Play around it
When you have spaces at the end. you can use beliow.
ProcessStr = ProcessStr.Replace(" ", "");
Emails = ProcessStr.TrimEnd(';');
Try this,
string Something1= Something.Substring(0, Something.Length - 1 );

How to extract string at a certain character that is repeated within string?

How can I get "MyLibrary.Resources.Images.Properties" and "Condo.gif" from a "MyLibrary.Resources.Images.Properties.Condo.gif" string.
I also need it to be able to handle something like "MyLibrary.Resources.Images.Properties.legend.House.gif" and return "House.gif" and "MyLibrary.Resources.Images.Properties.legend".
IndexOf LastIndexOf wouldn't work because I need the second to last '.' character.
Thanks in advance!
UPDATE
Thanks for the answers so far but I really need it to be able to handle different namespaces. So really what I'm asking is how to I split on the second to last character in a string?
You can use LINQ to do something like this:
string target = "MyLibrary.Resources.Images.Properties.legend.House.gif";
var elements = target.Split('.');
const int NumberOfFileNameElements = 2;
string fileName = string.Join(
".",
elements.Skip(elements.Length - NumberOfFileNameElements));
string path = string.Join(
".",
elements.Take(elements.Length - NumberOfFileNameElements));
This assumes that the file name part only contains a single . character, so to get it you skip the number of remaining elements.
You can either use a Regex or String.Split with '.' as the separator and return the second-to-last + '.' + last pieces.
You can look for IndexOf("MyLibrary.Resources.Images.Properties."), add that to MyLibrary.Resources.Images.Properties.".Length and then .Substring(..) from that position
If you know exactly what you're looking for, and it's trailing, you could use string.endswith. Something like
if("MyLibrary.Resources.Images.Properties.Condo.gif".EndsWith("Condo.gif"))
If that's not the case check out regular expressions. Then you could do something like
if(Regex.IsMatch("Condo.gif"))
Or a more generic way: split the string on '.' then grab the last two items in the array.
string input = "MyLibrary.Resources.Images.Properties.legend.House.gif";
//if string isn't already validated, make sure there are at least two
//periods here or you'll error out later on.
int index = input.LastIndexOf('.', input.LastIndexOf('.') - 1);
string first = input.Substring(0, index);
string second = input.Substring(index + 1);
Try splitting the string into an array, by separating it by each '.' character.
You will then have something like:
{"MyLibrary", "Resources", "Images", "Properties", "legend", "House", "gif"}
You can then take the last two elements.
Just break down and do it in a char loop:
int NthLastIndexOf(string str, char ch, int n)
{
if (n <= 0) throw new ArgumentException();
for (int idx = str.Length - 1; idx >= 0; --idx)
if (str[idx] == ch && --n == 0)
return idx;
return -1;
}
This is less expensive than trying to coax it using string splitting methods and isn't a whole lot of code.
string s = "1.2.3.4.5";
int idx = NthLastIndexOf(s, '.', 3);
string a = s.Substring(0, idx); // "1.2"
string b = s.Substring(idx + 1); // "3.4.5"

Categories