【发布时间】:2013-04-23 03:33:47
【问题描述】:
以下简单程序将查找用户输入的字符串中的最后一个字母,然后删除该点之后的所有内容。因此,如果一个人输入一个string....,则应该删除g 之后的所有内容。我有以下作为一个小程序:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter in the value of the string: ");
List<char> charList = Console.ReadLine().Trim().ToList();
int x = charList.LastIndexOf(charList.Last(char.IsLetter)) ;
Console.WriteLine("this is the last letter {0}", x);
Console.WriteLine("This is the length of the string {0}", charList.Count);
Console.WriteLine("We should have the last {0} characters removed", charList.Count - x);
for (int i = x; i < charList.Count; i++)
{
charList.Remove(charList[i]);
}
foreach (char c in charList)
{
Console.Write(c);
}
Console.ReadLine();
}
}
我已经尝试了很多变体,但没有一个能准确地写出来。这个特定程序的输入为string....,程序的输出为strin..,所以它以某种方式离开了它应该带走的东西,实际上它带走了它不应该带走的字母。任何人都可以说明为什么会这样吗?所需的输出应该是string。
【问题讨论】:
-
为什么不直接使用
input.Substring(0, x + 1)? -
@Grant Thomas:因为如果 x 不存在并且所有元素都被删除,x 可能是 -1,也许这就是意图,从“规范”中并不清楚。
-
@MichelKeijzers 这无关紧要。关键是所有的循环都是一场闹剧——值的验证是微不足道的。
标签: c# visual-studio-2010