Thomas S.
Thomas S.

Reputation: 184

Removing first word in a string

I'm looking for a simple way to remove the first word and the following space in a string.

//Before
str = "Hello world";

Something.

//After
str = "World";

Upvotes: 5

Views: 17014

Answers (3)

Sterbehilfe
Sterbehilfe

Reputation: 21

Another method is using ranges since C# 8.0

string str = "Hello World";

//One line
str = str[(str.Split()[0].Length + 1)..];

//Multiple lines
string firstWord = str.Split()[0];
int charsToSkip = firstWord.Length + 1;
str = str[charsToSkip..];

Upvotes: 1

ozanmut
ozanmut

Reputation: 3234

To remove first word, we need to find it, with Regex it would be cleaner to get it. Then remove is performed by substring.

var str = "EXEC STORED_PROC1";
var matchResult = Regex.Match(str, @"^([\w\-]+)");
var firstWord = matchResult.Value; // EXEC
var storedProc = str.Substring(firstWord.Length); // STORED_PROC1

Upvotes: 0

vivek kv
vivek kv

Reputation: 416

You can try this:

string word = "Hello World";
if (word.Length > 0)
{
   int i = word.IndexOf(" ")+1;
   string str=word.Substring(i);
   Response.Write(str);
}

Upvotes: 17

Related Questions