繁体   English   中英

如果您知道起始点和停止点但不知道 asp.net C# 中的中间点,如何拆分字符串

[英]How do you split a string if you know the start and stop point but not the middle in asp.net C#

我正在尝试删除可以随时更改的字符串部分。 这使得很难拆分字符串以移除所述部分。 在要删除的部分之前和之后有一个点是常数。

这是我能想到的准确显示示例的唯一方法(请忽略它是html的事实):

string text = 
"<ul>
<li>keep this text</li>
<li class=Known  unknown text  </li>
<li>keep this text</li>
</ul>";  

string [] splitPerams = {"","<li class=Known (im guessing a regex here) 
</li>"}

string [] results = 
text.Split(splitPerams,System.StringSplitOptions.RemoveEmptyEntries);

输出:

"<ul>
<li>keep this text</li>

<li>keep this text</li>
</ul>";

我知道有很多关于这个主题的类似问题,但它们都是不同的语言,我无法弄清楚如何在 c# 中实现逻辑。

编辑:我想我不允许删除它,所以我会尽我所能完全改写它以便更好地理解。

听起来您需要的不是分割,而是字符串的前端,因此使用substring应该可以做到。 由于您知道删除部分以什么字符开头,因此使用indexOf将很有用。

var str = "Hi My name is Mr. ???? from the usa.";
var newStr = str.Substring(0, str.IndexOf("Mr."));

玩弄它以获得您想要的确切长度。

参考:

https://docs.microsoft.com/en-us/dotnet/api/system.string.substring?view=netframework-4.7.2

https://docs.microsoft.com/en-us/dotnet/api/system.string.indexof?view=netframework-4.7.2

如果这对某人有帮助,那么当您知道未知部分之前和之后的部分时,这是从字符串中删除/拉出未知文本部分的方法。

string originalText = "Hi my name is Mr. Smith from the USA.";

string[] topPull = { "", "Mr." };
string[] bottomPull = { "from", "" };
string result;

string[] topPage = originalText.Split(topPull,StringSplitOptions.RemoveEmptyEntries);
string[] bottomPage = 
originalText.Split(bottomPull,StringSplitOptions.RemoveEmptyEntries);


//topPage[0] gives all text above topPull, but not topPull it's self
//bottomPull[1] gives all text below bottomPull, but not bottomPull it's self
//now that we have grabbed all the text above and below our known sections we need to 
//add in the known sections themselves, ie topPull and bottomPull

result = topPage[0] + topPull[1] + " " + bottomPull[0] + bottomPage[1];

输出:“嗨,我的名字是来自美国的先生。”


如果你只想保留中间文本,你可以这样做

string originalText = "Hi my name is Mr. Smith from the USA.";

string[] topPull = { "", "Mr." };
string[] bottomPull = { "from", "" };
string result;

string[] topPage = originalText.Split(topPull,StringSplitOptions.RemoveEmptyEntries);
string[] bottomPage = 
topPage[1].Split(bottomPull,StringSplitOptions.RemoveEmptyEntries);
result = bottomPage[0];

输出:“史密斯”;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM