一个字符串发生后删除文本 [英] Remove text after a string occurrence

查看:108
本文介绍了一个字符串发生后删除文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下格式的字符串:

I have a string that has the following format:

string sample = "A, ABC, 1, ACS,,"

正如你所看到的,也有5 OCCURENCES的字符。
我需要4发生后删除一切,这样最终的结果将是:

As you can see, there are 5 occurences of the , character. I need to remove everything after the 4th occurrence so that the final result will be:

string result = fx(sample, 4);
"A, ABC, 1, ACS"

是否有可能没有的foreach ? 。在此先感谢

Is it possible without a foreach? Thanks in advance.

推荐答案

您可以做这样的事情:

sample.Split(',').Take(4).Aggregate((s1, s2) => s1 + "," + s2).Substring(1);

这将在逗号分割的字符串,然后只需要前四部分(AABC1ACS),它们Concat的一个字符串总结(结果:,A,美国广播公司, 1,ACS)以及除第一个字符返回的一切。结果:A,ABC,1,ACS

This will split your string at the comma and then take only the first four parts ("A", " ABC", " 1", " ACS"), concat them to one string with Aggregate (result: ",A, ABC, 1, ACS") and return everything except the first character. Result: "A, ABC, 1, ACS".

这篇关于一个字符串发生后删除文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆