Reputation: 1181
Let's say I need to split string like this:
Input string: "My. name. is Bond._James Bond!" Output 2 strings:
I tried this:
int lastDotIndex = inputString.LastIndexOf(".", System.StringComparison.Ordinal);
string firstPart = inputString.Remove(lastDotIndex);
string secondPart= inputString.Substring(lastDotIndex + 1, inputString.Length - firstPart.Length - 1);
Can someone propose more elegant way?
Upvotes: 96
Views: 109608
Reputation: 884
A more concise version of Pierre-Luc's answer:
var s = "My. name. is Bond._James Bond!";
if (s.Split(".") is [.. var first, var last])
{
Console.WriteLine(string.Join(".", first));
Console.WriteLine(last);
}
The obvious drawback being the split-and-join with the same character for the first part. If you're only interested in the last part then you can use is [.., var last]
.
Upvotes: 0
Reputation: 5419
C# 8 introduced a new feature called ranges and indices, which offer a more concise syntax for working with strings.
string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');
if (idx != -1)
{
Console.WriteLine(s[..idx]); // "My. name. is Bond"
Console.WriteLine(s[(idx + 1)..]); // "_James Bond!"
}
This is the original answer that uses the string.Substring(int, int)
method. It's still OK to use this method if you prefer.
string s = "My. name. is Bond._James Bond!";
int idx = s.LastIndexOf('.');
if (idx != -1)
{
Console.WriteLine(s.Substring(0, idx)); // "My. name. is Bond"
Console.WriteLine(s.Substring(idx + 1)); // "_James Bond!"
}
Upvotes: 196
Reputation: 4636
More fun... Heck yeah!!
var s = "My. name. is Bond._James Bond!";
var firstSplit = true;
var splitChar = '_';
var splitStrings = s.Split(new[] { splitChar }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
if (!firstSplit)
{
return splitChar + x;
}
firstSplit = false;
return x;
});
Upvotes: 3
Reputation: 9201
You can also use a little bit of LINQ. The first part is a little verbose, but the last part is pretty concise :
string input = "My. name. is Bond._James Bond!";
string[] split = input.Split('.');
string firstPart = string.Join(".", split.Take(split.Length - 1)); //My. name. is Bond
string lastPart = split.Last(); //_James Bond!
Upvotes: 16
Reputation: 3183
string[] theSplit = inputString.Split('_'); // split at underscore
string firstPart = theSplit[0]; // get the first part
string secondPart = "_" + theSplit[1]; // get the second part and concatenate the underscore to at the front
EDIT: Following from the comments; this only works if you have one instance of the underscore character in your input string.
Upvotes: 8