-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).

Max
  • 12,622
  • 16
  • 73
  • 101
  • 1
    You are trying to re-invent what already exists in .NET! – Mo Patel Apr 29 '14 at 09:56
  • http://msdn.microsoft.com/en-us/library/system.string.split.aspx couldn't be more obvious. Have you googled at all? – Bart Teunissen Apr 29 '14 at 09:56
  • [how to split a string by a character in c#](https://www.google.co.in/search?q=how+to+split+a+string+by+a+character+in+c%23&oq=how+to+split+a+string+&aqs=chrome.1.69i57j69i59l2j0l3.6952j0j7&sourceid=chrome&es_sm=93&ie=UTF-8) – Microsoft DN Apr 29 '14 at 09:58
  • google + 5 seconds = http://www.dotnetperls.com/split – JPK Apr 29 '14 at 09: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? – Lasse V. Karlsen Apr 29 '14 at 09:58
  • 4
    Love how you all leap to pull the OP down, but then provide a flawed solution... – Martin Milan Apr 29 '14 at 09:59
  • He could split his string on the dot using string split function. (and yeah, this doesn't work if there are more that one dot in the path). – Bart Teunissen Apr 29 '14 at 10:02

1 Answers1

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('.'));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 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. – Martin Milan Apr 29 '14 at 09:56