Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide a string at first space

For a chat-bot, if someone says "!say " it will recite what you say after the space. Simple.

Example input:

!say this is a test

Desired output:

this is a test

The string can be represented as s for sake of argument. s.Split(' ') yields an array.

s.Split(' ')[1] is just the first word after the space, any ideas on completely dividing and getting all words after the first space?

I've tried something along the lines of this:

s.Split(' ');
for (int i = 0; i > s.Length; i++)
{
    if (s[i] == "!say")
    {
        s[i] = "";
    }
}

The input being:

!say this is a test

The output:

!say

Which is obviously not what I wanted :p

(I know there are several answers to this question, but none written in C# from where I searched.)

like image 346
Tako M. Avatar asked Feb 20 '12 18:02

Tako M.


People also ask

How do you split a string by first space?

We used the str. strip() method to remove any leading or trailing spaces from the string before calling the split() method. If you need to split a string only on the first whitespace character, don't provide a value for the separator argument when calling the str. split() method.

How do you divide a string with spaces?

You can split a String by whitespaces or tabs in Java by using the split() method of java. lang. String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces.

How do you split a string with a new line?

To split a string on newlines, you can use the regular expression '\r?\ n|\r' which splits on all three '\r\n' , '\r' , and '\n' . A better solution is to use the linebreak matcher \R which matches with any Unicode linebreak sequence. You can also split a string on the system-dependent line separator string.


1 Answers

Use the overload of s.Split that has a "maximum" parameter.

It's this one: http://msdn.microsoft.com/en-us/library/c1bs0eda.aspx

Looks like:

var s = "!say this is a test";
var commands = s.Split (' ', 2);

var command = commands[0];  // !say
var text = commands[1];     // this is a test
like image 61
Bryan Boettcher Avatar answered Sep 22 '22 01:09

Bryan Boettcher