简体   繁体   English

C#如何挑选字符串中的某些部分

[英]C# how to pick out certain part in a string

I have a string in a masked TextBox that looks like this: 我在蒙版的TextBox中有一个字符串,如下所示:

123.456.789.abc.def.ghi

"---.---.---.---.---.---"  (masked TextBox format when empty, cannot use underscore X(  )

Please ignore the value of the characters (they can be duplicated, and not unique as above). 请忽略字符的值(它们可以重复,并且如上所述不是唯一的)。 How can I pick out part of the string, say "789"? 我如何挑选字符串的一部分,例如“ 789”? String.Remove() does not work, as it removes everything after the index. String.Remove()不起作用,因为它会删除索引之后的所有内容。

Do you mean you want to obtain that part of the string? 您是说要获取字符串的那一部分吗? If so, you could use string.Split 如果是这样,您可以使用string.Split

string s = "123.456.789.abc.def.ghi";
var splitString = s.Split('.');
// splitString[2] will return "789"

You could simply use String.Split (if the string is actually what you have shown) 您可以简单地使用String.Split (如果字符串实际上是您所显示的)

string str = "123.456.789.abc.def.ghi";
string[] parts = str.Split('.');
string third = parts.ElementAtOrDefault(2); // zero based index
if(third != null)
    Console.Write(third);

I've just used Enumerable.ElementAtOrDefault because it returns null instead of an exception if there's no such index in the collection(It falls back to parts[2] ). 我刚刚使用了Enumerable.ElementAtOrDefault因为如果集合中没有这样的索引,它会返回null而不是异常(它会返回parts[2] )。

You could use Split in order to separate your values if the . 如果可以使用Split来分隔值. is always contained in your string. 始终包含在您的字符串中。

string input = "123.456.789.abc.def";

string[] mySplitString = input.Split('.');

for (int i = 0; i < mySplitString.Length; i++)
{
    // Do you search part here
}

尝试使用Replace

String.Replace("789", "")

Finding a string: 查找字符串:

string str="123.456.789.abc.def.ghi";
int i = str.IndexOf("789");
string subStr = str.Substring(i,3);

Replacing the substring: 替换子字符串:

  str = str.Replace("789","").Replace("..",".");

Regex: 正则表达式:

  str = Regex.Replace(str,"789","");

The regex can give you a lot of flexibility finding things with minimum code, the drawback is it may be difficult to write them regex可以给您很大的灵活性,可以用最少的代码查找内容,缺点是可能很难编写它们

If you know the index of where your substring begins and the length that it will be, you can use String.Substring() . 如果知道子字符串开始的索引及其长度,则可以使用String.Substring() This will give you the substring: 这将为您提供子字符串:

String myString = "123.456.789";
// looking for "789", which starts at index 8 and is length 3
String smallString = myString.Substring(8, 3);

If you are trying to remove a specific part of the string, use String.Replace() : 如果要删除字符串的特定部分,请使用String.Replace()

String myString = "123.456.789";
String smallString = myString.Replace("789", "");

var newstr = new String(str.where(c =>“ 789”))。tostring(); ..我想这会起作用,或者您可以像这样使用sumthng

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

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