Reputation: 453
I'm having a string like,
"abc kskd 8.900 prew"
need to Split
this string so that i get the result as "abc kskd"
and "8.900 prew"
how can i achieve this with C#
?
Upvotes: 1
Views: 178
Reputation: 2866
Something similar to what @Dominic Kexel provided, but only if you don't want to use linq.
string[] result = Regex.Split("abc kskd 8.900 prew", @"\w*(?=\d+\.\d)");
Upvotes: 0
Reputation: 4352
Try this,
public string[] SplitText(string text)
{
var startIndex = 0;
while (startIndex < text.Length)
{
var index = text.IndexOfAny("0123456789".ToCharArray(), startIndex);
if (index < 0)
{
break;
}
var spaceIndex = text.LastIndexOf(' ', startIndex, index - startIndex);
if (spaceIndex != 0)
{
return new String[] { text.Substring(0, spaceIndex), text.Substring(spaceIndex + 1) };
}
startIndex = index;
}
return new String[] {text};
}
Upvotes: 0
Reputation: 101032
straightforward with a regular expression:
var str = "abc kskd 8.900 prew";
var result = Regex.Split(str, @"\W(\d.*)").Where(x => x!="").ToArray();
Upvotes: 0
Reputation: 63722
This should do if you don't need to do something complicated:
var data = "abc kskd 8.900 prew";
var digits = "0123456789".ToCharArray();
var idx = data.IndexOfAny(digits);
if (idx != -1)
{
var firstPart = data.Substring(0, idx - 1);
var secondPart = data.Substring(idx);
}
IndexOfAny
is actually very fast.
This could also be modified to separate the string into more parts (using the startIndex
parameter), but you didn't ask for that.
Upvotes: 2
Reputation: 101680
Get the index of first digit using LINQ
then use Substring
:
var input = "abc kskd 8.900 prew";
var index = input.Select( (x,idx) => new {x, idx})
.Where(c => char.IsDigit(c.x))
.Select(c => c.idx)
.First();
var part1 = input.Substring(0, index);
var part2 = input.Substring(index);
Upvotes: 3