i need to print the first and the last word in a string here is what i've tried
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string first = str.Substring(0, str.IndexOf(" "));
string last = str.Substring(str.LastIndexOf(' '),str.Length-1);
Console.WriteLine(first + " " + last);
when i run the code this massage appear
Unhandled Exception: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length at System.String.Substring(Int32 startIndex, Int32 length) at ConsoleApp1.Tar13.Main() in C:\Users\User\source\repos\ConsoleApp1\ConsoleApp1\Tar13.cs:line 16
i dont know what is the problem
If this is homework, don't hand this in unless you really understand it, have done LINQ (or have a supervisor that approves of off-piste learning and you're prepared to acknowledge you got outside assistance/did background learning) and are willing to explain it if asked:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string[] bits = str.Split();
Console.WriteLine(bits.First() + " " + bits.Last());
For a non-LINQ version:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string first = str.Remove(str.IndexOf(' '));
string last = str.Substring(str.LastIndexOf(' ') + 1);
Console.WriteLine(first + " " + last);
Bear in mind that these will crash if there are no spaces in the string - the Split version won't
Look at String Remove and Substring
If you want to robust things up so it doesn't crash:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
if(str.Contains(" ")){
string first = str.Remove(str.IndexOf(' '));
string last = str.Substring(str.LastIndexOf(' ') + 1);
Console.WriteLine(first + " " + last);
}
I'll leave a "what might we put in an else ?" in that last code block, as an exercise for you:)
you can split the string and get first and last...
var s = str.Split(' ', StringSplitOptions.RemoveEmptyEntries );
if(s.Length >= 2)
{
var first = s.First();
var last = s.Last();
Console.WriteLine($"{first} {last}");
}
In general case when sentence can contain punctuation , not necessary English letters you can try regular expressions . Let's define
Word is non empty sequence of letters and apostrophes
And so we have
Code:
using System.Linq;
using System.Text.RegularExpressions;
...
private static (string first, string last) Solve(string value) {
if (string.IsNullOrWhiteSpace(value))
return ("", "");
var words = Regex
.Matches(value, @"[\p{L}']+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
return words.Length > 0
? (words[0], words[words.Length - 1])
: ("", "");
}
Demo:
string[] tests = new string[] {
"Simple string", // Simple Smoke Test
"Single", // Single word which is both first an last
"", // No words at all; let's return empty strings
"words, punctuations: the end.", // Punctuations
"Русская (Russian) строка!", // Punctuations, non-English words
};
var result = string.Join(Environment.NewLine, tests
.Select(test => $"{test,-30} :: {Solve(test)}"));
Console.Write(result);
Outcome:
Simple string :: (Simple, string)
Single :: (Single, Single)
:: (, )
words, punctuations: the end. :: (words, end)
Русская (Russian) строка! :: (Русская, строка)
If you want to get the last and first-word try to do the following:
string sentence = "Hello World"; //Sentence
string first = sentence.Split(" ")[0]; //First word
string last = sentence.Split(" ")[sentence.Split(" ").Length -1]; //Last word
Console.WriteLine(first + " "+ last);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.