Question with replacing a string with C #

Quick question. I have a list that is populated from a list of directories. Each file contains its own name and ~ #####. I am trying to read all this into a string and not replace anything with ~ ####. #### can be a number from 1 to 6 and can be from 0 to 9. Here is the code I use:

string listItem = (listBox1.SelectedItem.ToString().Replace("~*",""));

Example:

Here223~123  --->  Here
Here224~2321 ----> Here

I cannot replace any number because I need numbers before ~

+5
source share
5 answers

What about:

string listItem = 
      listBox1.SelectedItem.ToString().Substring(0, 
           listBox1.SelectedItem.ToString().IndexOf("~"));
+4
source

Try

listItem.Split("~")[0]

This should give you the first line in the string array, so after that you lose the tilde and the ending line.

+12
source

string listItem = Regex.Replace(listBox1.SelectedItem.ToString(), "~[0-9]{1,6}", string.Empty);

( , , !)

+6

, Substring (int startIndex, int lenght):

string listItem = listBox1.SelectedItem.toString();
listItem = listitem.SubString(0, listItem.IndexOf("~"));
+4

, string.replace

so divide by "~" or use regex

+1
source

All Articles