Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip starting 2 words from a string in c#

Tags:

c#

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.

like image 208
Baran Saeed Avatar asked Mar 10 '23 20:03

Baran Saeed


1 Answers

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));
like image 143
kat1330 Avatar answered Mar 19 '23 06:03

kat1330