How to ignore the first 2 words of a string
like:
String x = "hello world this is sample text";
in this the first two words are hello world, so i want to skip them, but next time maybe the words will not be the same, like maybe they become, "Hakuna Matata", but the program should also skip them.
P.S : don't not suggest remove characters it won't work here i guess, because we don't know what is the length of these words, we just want to skip the first two words. and print the rest.
Please try this code:
String x = "hello world this is sample text";
var y = string.Join(" ", x.Split(' ').Skip(2));
It will split string by spaces, skip two elements then join all elements into one string.
UPDATE:
If you have extra spaces than first remove extra spaces and remove words:
String x = "hello world this is sample text";
x = Regex.Replace(x, @"\s+", " ");
var y = string.Join(" ", x.Split(' ').Skip(2));
UPDATE:
Also, to avoid extra spaces as suggested by Dai (in below comment) I used Split() with StringSplitOptions:
String x = "hello world this is sample text";
var y = string.Join(" ", x.Split((char[])null, StringSplitOptions.RemoveEmptyEntries).Select(i => i.Trim()).Skip(2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With