Reputation: 13
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 inbetween 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#
Upvotes: 1
Views: 94
Reputation: 3699
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];
}
Upvotes: 0
Reputation: 3681
U can read all as one string then split with "vs" seperator, then ull get table of 2 strings that u need
Upvotes: 1
Reputation: 56717
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.
Upvotes: 1
Reputation: 50855
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];
}
Upvotes: 5
Reputation: 5614
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.
Upvotes: 2