-4

How can i get the string "tulip" from the string "tulip.jpg" using Split function in c#?

string str = "tulip.jpg";

I store the result "tulip" in str1(string type valiable).

7
  • 1
    You are trying to re-invent what already exists in .NET! Commented Apr 29, 2014 at 9:56
  • msdn.microsoft.com/en-us/library/system.string.split.aspx couldn't be more obvious. Have you googled at all? Commented Apr 29, 2014 at 9:56
  • how to split a string by a character in c# Commented Apr 29, 2014 at 9:58
  • 2
    @BartTeunissen And it couldn't be more obvious that the string contains a filename, in which case string.split is entirely the wrong answer. Have you read the question at all? Commented Apr 29, 2014 at 9:58
  • 4
    Love how you all leap to pull the OP down, but then provide a flawed solution... Commented Apr 29, 2014 at 9:59

1 Answer 1

10

That's a filename, so i wouldn't use String.Split but the Path-methods:

string fileNameOnly = Path.GetFileNameWithoutExtension("tulip.jpg");

For what it's worth: fileNameOnly = "tulip.jpg".Split('.')[0];

This will be a problem if the name also contains dots.

So if you insist on string methods String.Substring or String.Remove would be better:

fileNameOnly = fileName.Remove(fileName.LastIndexOf('.'));
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer - if your problem is within the domain of filenames / paths, and the functionality exists within the Framework to allow you to do the job in that context, then use it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.