Remove string from one character to another c#

时间:2017-06-15 10:06:46

标签: c#

I have the following string:

"Downloads-Size:2090493403 bytes, Number of files: 39\Folder1-Size:748334 bytes, Number of files: 3\someFile.exe-Size: 545454 bytes"

What i need is to delete from "-Size: ... till \" so that the string should look like Downloads\Folder1\someFile.exe

I appreciate all help.

Here is what i did so far

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {

        folderPath = e.Node.FullPath;

        String treeNode = treeView1.SelectedNode.ToString().Replace("TreeNode: ", String.Empty);

        String treeNodeName = treeNode.Substring(0, treeNode.LastIndexOf('-'));

        MessageBox.Show(folderPath);
      }

3 个答案:

答案 0 :(得分:0)

You can use the split function like this

        string str = @"Downloads-Size:2090493403 bytes, Number of files: 39\Folder1-Size:748334 bytes, Number of files: 3\someFile.exe-Size: 545454 bytes";
        string[] strs = str.Split(',');

        string result = strs[0].Split('-')[0]
            + "\\" + strs[1].Split('\\')[1].Split('-')[0]
            + "\\" +  strs[2].Split('\\')[1].Split('-')[0];

You will need some error checking in production code, in case the string is not always in the correct format.

答案 1 :(得分:0)

You could use String.Split and String.Join.

var text = @"Downloads-Size:2090493403 bytes, Number of files: 39\Folder1-Size:748334 bytes, Number of files: 3\someFile.exe-Size: 545454 bytes";
var splits = text.Split(new string[] {"-Size", "\\"}, StringSplitOptions.None);  
var output  =  string.Join("\\", splits.Where((x, i) => i % 2 == 0));

答案 2 :(得分:0)

string text = @"Downloads-Size:2090493403 bytes, Number of files: 39\Folder1-Size:748334 bytes, Number of files: 3\someFile.exe-Size: 545454 bytes";
while (text.Contains("-Size")) {
    int start = text.IndexOf("-Size");
    int end = text.IndexOf(@"\", start);
    int length = end < 0 ? text.Length - start : end - start;
    string remove = text.Substring(start, length);
    text = text.Replace(remove, string.Empty);
}