hi please help me with a question I had for class: Write a program that asks the user for a 5-word sentence. Output the first character of each word to the terminal. **I'm a highschool beginner so I used functions that I know already
this is what I've tried but Its definitely not correct:
Console.Write( "PLEASE ENETER A 5 WORD SENTNCE: ");
string sent = Console.ReadLine();
int firstIndexTwo= sent.IndexOf(' ') 1;
int endIndexTwo= 1;
string second= sent.Substring(firstIndexTwo, endIndexTwo);
int firstIndexThree= endIndexTwo 1;
int endIndexThree= sent.IndexOf(' ');
string third= sent.Substring(firstIndexThree, 1);
int firstIndexFour= endIndexThree 1;
int endIndexFour= sent.IndexOf(' ');
string fourth=sent.Substring(firstIndexFour, 1);
int firstIndexFive= endIndexTwo 1;
string fifth= sent.Substring(firstIndexFive);
System.Console.Write(sent[0]);
System.Console.Write(second[0]);
System.Console.Write(third[0]);
System.Console.Write(fourth[0]);
System.Console.Write(fifth[0]);
CodePudding user response:
Your approach looks quite static. You should try to solve your problem in a more flexible way. Here you can find a simple, compact and generic example how to get the first characters of each word:
string input = Console.ReadLine();
string[] words = input.Split(' ');
IEnumerable<char> firstCharacters = words.Select(w => w[0]);
Console.WriteLine(string.Join(" - ", firstCharacters));
The idea behind it is very simple:
- Get the users inut
- Split the input by spaces
- Take the first character of each of this splitted parts
- Combine the first characters separated with ' - ' and print it
Depending on your requirements, you can adapt it to verify the number of words entered by adding a simple check like:
if (words.Length != 5)
{
Console.WriteLine("Please enter 5 words");
return;
}
CodePudding user response:
I agree with Fruchtzwerg bu his code is a little complicated for beginner. here a simplified version where I replace the last two line with a simple loop
var text = "this phrase have five words";
string[] words = text.Split(' ');
for(var i = 0; i < words.Length ; i ){
Console.WriteLine("word " i " : " words[i][0]);
}
in c# a string is an array of char, so you can access it with 'string[x]' x is the index of the letter you want