简体   繁体   English

如何从未定义的字符串长度中提取子字符串?

[英]how to extract substring from a undefined length of string?

Substring these string:- 这些字符串的子字符串:

1. ZZ111122
2. ZZZZ222111
3. ZZZZZZZ333
4. ZZZ111333

I have these kind of strings. 我有这类琴弦。 This value is always starting with Z. And after Z its always either 1 or 2 or 3. But i dont know the number of Zs in the string. 此值始终以Z开头。在Z之后,其值始终为1或2或3。但是我不知道字符串中Z的数量。 So how can i extract all Z from the string 那么我怎样才能从字符串中提取所有Z

I don't know if I understood right. 我不知道我是否理解正确。 If you have "ZZZZ222111" and want only "222111", do it: 如果您具有“ ZZZZ222111”,并且只需要“ 222111”,请执行以下操作:

string test = "ZZZZ222111";
test = test.Substring(test.LastIndexOf("Z") + 1);

If you want only "ZZZZ", do it: 如果只需要“ ZZZZ”,请执行以下操作:

string test = "ZZZZ222111";
test = test.Substring(0, test.LastIndexOf("Z"));

Both ways are very simple. 两种方法都很简单。 No need of loops or regular expressions. 无需循环或正则表达式。

听起来您将要为此使用正则表达式

使用String.Trim函数:

ZeroZValue = stringValue.Trim('Z');

This is not difficult. 这并不困难。 I recommend processing the text line by line. 我建议逐行处理文本。

You can loop the string character by character. 您可以逐个字符地循环字符串。 You can use regular expressions. 您可以使用正则表达式。 Or you could use my sscanf() replacement class for C# . 或者,您可以将我的sscanf()替换类用于C#

String test = "ZZ111122";
String zOnly = test.Substring(0, test.IndexOfAny("123".ToCharArray()));

Take advantage of IndexOfAny() . 利用IndexOfAny() I am assuming you want only Z's left over ("extract all Z from the string"). 我假设您只想保留Z的剩余部分(“从字符串中提取所有Z”)。

int start = someString.IndexOf("Z");
int end = someString.LastIndexOf("Z");
someString.Substring(start , end - start);

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

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