删除在字符串中找到索引之前的一定数量的字符

问题描述 投票:0回答:5

我有一个字符串,需要从中删除某些字符。

string note =“ TextEntry_Slide_7 |记事本一,我将在各处输入文本:)| 250887 | 0 ^ TextEntry_Slide_10 |记事本二:wrilun3q 4p9834m ggddi:(| 996052 | 2 ^ TextEntry_Slide_14 || 774159 | 4 ^ TextEntry_Slide_16 | tnoinrgb rt trn n | 805585 | 5“

我要删除^字符以及^字符后面的9个字符。因此该字符串将如下所示:

string note =“ TextEntry_Slide_7 |记事本一,我将在各处输入文本:)TextEntry_Slide_10 |记事本二:wrilun3q 4p9834m ggddi:(TextEntry_Slide_14 | TextEntry_Slide_16 | tnoinrgb rt trn n | 805585 | 5”

此外,我还需要删除字符串末尾的最后9个字符:

string note =“ TextEntry_Slide_7 |记事本一,我将在各处输入文本:)TextEntry_Slide_10 |记事本二:wrilun3q 4p9834m ggddi:(TextEntry_Slide_14 | TextEntry_Slide_16 | tnoinrgb rt trn n”

我已经删除了原本在字符串注释中的大量其他内容,但是我对如何执行上述操作感到很困惑。

[我发现了^字符的索引,例如note.IndexOf("^"),但是我不确定下一步要删除前面的9个字符。

任何帮助将不胜感激:)

c# string replace substring indexof
5个回答
3
投票

一种简单的方法是Regex.Replace(note, ".{9,9}\\^", "");

并且删除最后9个字符的明显方法是note.Substring(0, note.length - 9);


1
投票

当然,您需要做的是:

string output = Regex.Replace(note, @".{9}\^", string.Empty);
// remove last 9
output = output.Remove(output.Length - 9);

1
投票

首先,我们使用正则表达式去除插入符号和前面的9个字符。

 var stepOne = Regex.Replace(input, @".{9}\^", String.Empty);

然后我们只丢弃最后的9个字符。

 var stepTwo = stepOne.Remove(stepOne.Length - 9);

并且您可能应该添加一些错误处理-例如,如果字符串在第一步之后少于9个字符。


0
投票

如果使用.IndexOf("^"),则可以将该结果/位置存储到一个临时变量中,然后使用几个.Substring()调用来重建您的字符串。

尝试类似的东西:

int carotPos = note.IndexOf("^");
while (carotPos > -1) {
    if (carotPos <= 9) {
        note = note.Substring(carotPos);
    } else {
        note = note.Substring(0, (carotPos - 9)) + note.Substring(carotPos);
    }
    carotPos = note.IndexOf("^");
}

这将在字符串中找到第一个^,并删除前面的前9个字符(包括^)。然后,它将在字符串中找到下一个^并重复直到没有剩余的为止。

要从字符串中删除最后9个字符,请再执行.Substring()

note = note.Substring(0, (note.Length - 9));

0
投票

我不确定您的语言是什么,但是在vb.net中,我为此经常使用了instr()函数。 instr告诉您在另一个字符串中找到字符串的第一个匹配项的位置,如果找不到字符串,则返回0或负数。

[接下来,如果要在vb.net中剥离字符串,可以将mid()函数与len()函数结合使用,轻松地做到这一点,len告诉长度以及与instr一起,您可以从字符串中计算出所需的内容。

如果您想在C#中执行此操作,请检查以下URL:http://www.dotnetcurry.com/ShowArticle.aspx?ID=189

© www.soinside.com 2019 - 2024. All rights reserved.