Reputation: 13
I am writing a program to scramble a user entered phrase. I have most of it coded, but I want to store the string of the user entered phrase into and array, with each word of the phrase stored as a separate element. It seems like it would be a simple thing to do, but I just can't think of a way to do it. Can someone help me?
This is what it looks like so far:
static void Main(string[] args)
{
bool success = false;
string phrase = "";
string [] phraseArray;
Console.WriteLine("Welcome to the Word Scrambler!\n\n");
do
{
Console.WriteLine("Enter a phrase between 10 and 60 character long:\n\t");
phrase = Console.ReadLine();
if (phrase.Length - 1 <= 10 || phrase.Length - 1 >= 60)
{
Console.WriteLine("You must enter a phrase with a length between 10 and 60!");
success = false;
}
phraseArray = new string[phrase.Length - 1];
// String (phrase) into string [] phraseArray ?
Console.WriteLine("See below for your scrambled phrase:");
for (int i = 0; i < phrase.Length - 1; i++)
{
Console.Write("{0} ", phraseArray[i]);
}
Console.WriteLine("Press any key to scramble another word or the 'Esc' key to exit...");
if (Console.ReadKey(true).Key == ConsoleKey.Escape)
success = false;
} while (!success);`
Upvotes: 1
Views: 1959
Reputation: 3965
Every time you want to save phrase just do this:
phrase+= inputString + ";";
After that you can split phrase into string array:
string[] yourStringArray = phrase.split(';');
Upvotes: 0
Reputation: 63065
phraseArray = phrase.Split();
OR If you need to remove empty strings
phraseArray = phrase.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
Upvotes: 1
Reputation: 2427
Consider the following...
string[] words = sentence.Split(' ');
Good Luck!
Upvotes: 2