Link to home
Start Free TrialLog in
Avatar of Alex E.
Alex E.

asked on

string separate in two variables asp.net c#

We have a lot of string variables in an asp.net c# application with values like "document.doc"' "powernt,ppt", school.xls"', "theme.pdf" and son on. How can we separate in code behind in 2 new strings each variable and that 2 new variables must be: First new string is the name before the "." and the second string the extension or the name after the "."

 For example using one example I wrote:

main string : "document.doc" and this we want to store in 2 new variables like this:
first new variable value "document"
second new variable "doc"

In short is like separate the name and extension in 2 new variables.

What command or script can be used to do that in codebehind?
Avatar of zephyr_hex (Megan)
zephyr_hex (Megan)
Flag of United States of America image

You can use the Split() method.

Here is a Fiddle Demo

using System;
					
public class Program
{
	public static void Main()
	{
		var myString = "document.doc";
		var mySplit = myString.Split('.');
		for(int i = 0; i < mySplit.Length; i++) 
		{
			Console.WriteLine(mySplit[i]);
		}
	}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of zephyr_hex (Megan)
zephyr_hex (Megan)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And as a side note, it may be useful to use a Class object instead of a variable

Fiddle Demo

using System;
using System.IO;
					
public class Program
{
	public static void Main()
	{
		MyThing thing = new MyThing("document.doc");
		Console.WriteLine(thing.FileName);
		Console.WriteLine(thing.Extension);
	}
	
	public class MyThing 
	{
		public string FullName { get; set; }
		public string FileName { get; set; }
		public string Extension { get; set; }
		
		public MyThing(string thing)
		{
			FullName = thing;
			FileName = Path.GetFileNameWithoutExtension(thing);
			Extension = Path.GetExtension(thing).Replace(".","");
		}
	}
}

Open in new window

SOLUTION
Avatar of Dustin Saunders
Dustin Saunders
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alex E.
Alex E.

ASKER

Thank you worked perfect!