woo*_*gie 6 c# visual-studio-2010
以下简单程序将找到用户输入的字符串中的最后一个字母,然后删除该点之后的所有内容.所以,如果一个人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();
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了很多这方面的变化,没有一个让它完全写.这个特殊的程序输入string....了程序的输出,strin.. 所以不知怎的,它留下它应该带走的东西,它实际上带走了不应该的字母.任何人都可以说明为什么会这样吗?所需的输出,应该是string.
试试这个:
string input = Console.ReadLine(); // ABC.ABC.
int index = input.Select((c, i) => new { c, i })
.Where(x => char.IsLetter(x.c))
.Max(x => x.i);
string trimmedInput = input.Substring(0, index + 1);
Console.WriteLine(trimmedInput); // ABC.ABC
Run Code Online (Sandbox Code Playgroud)
Substring我认为简单地用户输入会更直接string。因此,请考虑以下修改后的代码:
class Program
{
static void Main(string[] args)
{
Console.Write("Enter in the value of the string: ");
var s = Console.ReadLine().Trim();
List<char> charList = s.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);
Console.WriteLine(s.Substring(0, x + 1);
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们存储用户输入的值s,找到字母的最后一个索引,然后Substring在写入控制台时通过该字母。
| 归档时间: |
|
| 查看次数: |
749 次 |
| 最近记录: |