patterncsharpMinor
Getting a substring of a delimited string
Viewed 0 times
substringstringgettingdelimited
Problem
I have some underscore-delimited strings like
then I get:
This is the C# code I'm using:
I'm wondering if there's a simpler way to rewrite this, possibly using extension methods.
abc_def_ghi. I would like to get a substring out of the string made of one or more delimited substrings, so that if I call:getUnderscoreSubstring("abc_def_ghi",2)then I get:
abc_defThis is the C# code I'm using:
public string getUnderscoreSubstring(string fullStr,int substringCount)
{
string[] splitArray = fullStr.Split('_');
if (substringCount>splitArray.Count())
{
return null;
}
else
{
string output = "";
for(int c=0;c<substringCount;c++)
{
output += splitArray[c];
if (c<substringCount-1)
{
output += "_";
}
}
return output;
}
}I'm wondering if there's a simpler way to rewrite this, possibly using extension methods.
Solution
Yes, you can definitely simplify this.
Calling it is as easy as
What does it do?
Very short and sexy!
This doesn't take the
Now, some comments about your code:
public string GetSubstring(string input, int count, char delimiter)
{
return string.Join(delimiter.ToString(),
input.Split(delimiter).Take(count));
}Calling it is as easy as
GetSubstring(input, 2, '_')What does it do?
- Split the input string by the delimiter
- Take the amount of substrings you want
- Glue the selected substrings together with your delimiter
Very short and sexy!
This doesn't take the
substringCount > splitArray.Count() in account but you can easily add that yourself: just split up the oneliner and add the appropriate check.Now, some comments about your code:
- Use
.Lengthinstead of.Count()when possible: the former will always be an O(1) operation, the latter sometimes an O(n). It won't make a difference here since an array implementsICollection(and will use this optimization) but it's a good practice to observe.
- Returning
nullis typically avoided for good reasons, consider an empty string or exception instead (don't go for the exception in this case).
- I prefer to explicitly use
string.Emptyrather than an empty string to avoid confusion.
- Write your variable names in full -- nobody is helped by abbreviating them.
- Use a StringBuilder to concatenate in a loop to avoid unnecessary string object creating.
- Leave some space in your code, it will read more fluently.
Code Snippets
public string GetSubstring(string input, int count, char delimiter)
{
return string.Join(delimiter.ToString(),
input.Split(delimiter).Take(count));
}Context
StackExchange Code Review Q#88509, answer score: 8
Revisions (0)
No revisions yet.