且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除字符串中的最后一个单词?

更新时间:2023-11-10 10:03:04

请勿附加这样的字样。而是使用下面的代码。



Don't append the word like this. Instead use below code.

List<string> names=new List<string>();
names.Add("John");
names.Add("Mike");
names.Add("Tony");
string friends = string.Join(" and ",names);
MessageBox.Show(friends);


你好,

你可以使用上面提到的这2个解决方案。但是如果你知道Linq然后使用以下Code.I有累了&测试它工作正常。

JUst添加Linq的NameSpace如果它没有。

Hello ,
You Can Use This 2 solutions mention above.But If you are aware about the Linq Then Use The Following Code.I Have Tired & Tested It Works Fine.
JUst Add a NameSpace Of Linq If It Does Not have.
using System.Linq;



你的代码:


YOur Code:

string friends = string.Empty;
List<string> names=new List<string>();
names.Add("John");
names.Add("Mike");
names.Add("Tony");



然后使用聚合函数


Then using The Aggregrate Function

friends = (names.Aggregate((i, j) => i + " and " + j)).ToString();
//friends=John and Mike and Tony
MessageBox.Show(friends);





试试这个

希望它能帮助你。快乐的编码



Try This
Hope It Helps You.Happy Coding


您可以使用 http://www.dotnetperls.com/lastindexof [ ^ ]和子串 [ ^ ]



You can use http://www.dotnetperls.com/lastindexof[^] and Substring[^]

 public static void Main(string[] args)
    {

       string friends=string.Empty;
List<string> names = new List<string>();
names.Add("John");
names.Add("Mike");
names.Add("Tony");
foreach(string name in names)
{
friends+=name+" and ";
}
int position = friends.LastIndexOf("and");
string result = friends.Substring(0, position);
Console.WriteLine(result);
        Console.ReadKey();

    }





编辑:





Edited:

List<string> names = new List<string>();
        names.Add("John");
        names.Add("Mike");
        names.Add("Tony");

        string friends = string.Join(" and ",names.ToArray());
        Console.WriteLine(friends);
        Console.ReadKey();