如何删除字符串中的最后一个单词? [英] How do I remove the last word in a string?
本文介绍了如何删除字符串中的最后一个单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,它会附加一个单词'和'。最后,当字符串完成后,我需要删除最后的'和'。
例如:
I have a string which gets appended very time with a word 'and'. Finally, when the string is complete, I need to remove the final 'and'.
eg:
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";
}
MessageBox.Show(friends);
结果如下:John和Mike and Tony和
我需要删除最终的和。
请在这里帮助我
提前致谢
This gives the result:"John and Mike and Tony and"
I need to remove the final "and".
Please help me here
Thanks in advance
推荐答案
请勿附加这样的字样。而是使用下面的代码。
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();
这篇关于如何删除字符串中的最后一个单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文