简体   繁体   中英

C# how to pick out certain part in a string

I have a string in a masked TextBox that looks like this:

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"? String.Remove() does not work, as it removes everything after the index.

Do you mean you want to obtain that part of the string? If so, you could use 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 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] ).

You could use Split in order to separate your values if the . 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

If you know the index of where your substring begins and the length that it will be, you can use 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 myString = "123.456.789";
String smallString = myString.Replace("789", "");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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