简体   繁体   中英

what is the best way to split a string

I have file name which look like

Directory\\name-secondName-blabla.txt

If I using string .split my code need to know the separator I am using, But if in some day I will replace the separator my code will break

Is the any build in way to split to get the following result?

Directory
name
secondNmae
blabla
txt

Thanks

Edit My question is more general than just split file name, is splitting string in general

The best way to split a filename is to use System.IO.Path

You're not clear about what to do with directory1\\directory2\\ ,
but in general you should use this static class to find the path , name and suffix parts.

After that you will need String.Split() to handle the - separators, you'll just have to make the separator(s) a config setting.

You can make an array with seperators:

string value = "Directory\name-secondName-blabla.txt";
char[] delimiters = new char[] { '\\', '-', '.' };
string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
var filepath = @"Directory\name-secondName-blabla.txt";
var tokens = filepath.Split(new[]{'\\', '-'});

If you're worried about your separator token changing in the future, set it as a constant in a settings file so you only have to change it in one place. Or, if you think it is going to change regularly, put it in a config file so you don't have to release new builds every time.

正如Henk上面提到的那样,使用System.IO.Path及其静态方法,如GetFileNameWithoutExtenstionGetDirectoryName等。看看这个链接: http//msdn.microsoft.com/en-us/library/system.io.path的.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM