开发者

How can I read input as two different answers

Say I get the following question

Console.WriteLine("Which teams have faced eachother? - use Red vs Blue format");

Then my answer to the question above will have two teams. But how can read them as two seperate? So that i only read [Red] [Blue], but the "vs" part inbe开发者_JAVA技巧tween as to be there.

I hope my you understood what I am trying to say. My english is not great.

best regards,

ps, as you can tell I am pretty new in programming.

edit: oh and this is all in C#


You can use String.Split():

var answers = userInput.Split(new String[] { "vs" }, StringSplitOptions.RemoveEmptyEntries);
if (answers.Length == 2) {
    var red = answers[0];
    var blue = answers[1];
}


There are many option you can use Split function to make it array and remove "vs" or simple use String.Replace("vs","") function to replace the "vs" string with blank value.


You can try using a regular expression:

Match m = Regex.Match("^(?<team1>\.+) vs (?<team2>\.+)$", userInput);
if (m.Success)
{
    string team1 = m.Groups["team1"].Value;
    string team2 = m.Groups["team2"].Value;
}

Please note that this may not be 100% syntactically correct - you have to refer to IntelliSense a bit - for example, I'm not sure whether the pattern is the first or the second parameter in Match, but I'm sure you get the picture.


U can read all as one string then split with "vs" seperator, then ull get table of 2 strings that u need


Use the String.Split function, as others have suggested. This will split your string into an array of strings. Then, identify which string in the array is the 'vs' string. Take the value of the index prior to 'vs' and after 'vs'. For example:

string input = "Which teams have faced eachother? - use Red vs Blue format";
string[] inputArray = input.Split( ' ' );

int vsLocation = 0;

for ( int i = 0; i < inputArray.Length; i++ ) {
    if ( inputArray[i] == "vs" ) {
        vsLocation = i;
        break;
    }
}

if ( vsLocation > 0)  {
    string team1 = inputArray[vsLocation - 1];
    string team2 = inputArray[vsLocation + 1];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜