Home > front end >  Cut out part of string c# [closed]
Cut out part of string c# [closed]

Time:10-06

Let's say I have a couple of strings in a List of strings

"hoodie-blue.png"
"hoodie-red.png"
"hoodie-purple.png"

and I want to cut out the parts of the strings where it says the color so I end up with the colors in a new List of strings

"blue"
"red"
"purple"

I can't quite wrap my head around on how to do it.

CodePudding user response:

Another couple of options:

Split each string on - and . and take the second entry:

yourlist.Select(s => s.Split('.','-')[1])

Use the indexes and ranges feature of C# 8 to cut the string between start 7 and end-4

yourlist.Select(s => s[7..^4])

That above is equivalent to the older school form:

yourlist.Select(s => s.Remove(s.Length-4).SubString(7))

CodePudding user response:

try this

var list = new List<string> {
    "hoodie-blue.png",
    "hoodie-red.png",
    "hoodie-purple.png"
    };

     List<string> colours = list.Select(l => l.Replace("hoodie-", "").Replace(".png", ""))
    .ToList();

// or 

    List<string> colours = list.Select(l =>  l.Split(".")[0].Substring("hoodie-".Length))
.ToList();

output

    blue
    red
    purple

  • Related