c# - 字符串c#中的最后一个单词和第一个单词
问题描述
我需要打印字符串中的第一个和最后一个单词这是我尝试过的
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);
当我运行代码时,这个按摩出现
未处理的异常:System.ArgumentOutOfRangeException:索引和长度必须引用字符串中的位置。参数名称:C:\Users\User\source\repos\ConsoleApp1\ConsoleApp1\Tar13.cs:line 16 中 ConsoleApp1.Tar13.Main() 处 System.String.Substring(Int32 startIndex, Int32 length) 的长度
我不知道是什么问题
解决方案
如果这是家庭作业,除非你真的理解它,否则不要交出它,已经完成了 LINQ(或者有一个批准越野学习的主管,并且你准备承认你得到了外部帮助/进行了背景学习)并且是如果被问到愿意解释:
Console.WriteLine("please enter a string");
string str = Console.ReadLine();
string[] bits = str.Split();
Console.WriteLine(bits.First() + " " + bits.Last());
对于非 LINQ 版本:
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);
请记住,如果字符串中没有空格,这些将崩溃 - 拆分版本不会
如果您想增强功能使其不会崩溃:
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);
}
我会留下一个“我们可以在else中放什么?” 在最后一个代码块中,作为你的练习:)
推荐阅读
- response - 在 Wicket 7.10 中写入响应后重定向
- python - Python SQLAlchemy 和 SQLite - 外键
- r - 数据框:对某些变量表示平均值,忽略但保留其他变量
- mysql - 优化具有 17 亿条记录的 MySQL 脚本
- javascript - remove active class on the next element
- jquery - Angularjs 与 iCheck jquery 冲突,无法从单选按钮获取数据
- ios - 如何在 swift 4 中将徽章放在 UIBarButtonItem 上?
- express - 尝试呈现翡翠模板时无法读取未定义的属性“用户名”
- c# - 从 Visual Studio 2017 使用 OData 服务
- agile - 如何在 Tuleap 中恢复看板仪表板?