简体   繁体   中英

How do get the first occurrence of a char in Substring

I'm trying to get the first occurrence in my substring start point:

string dir = Request.MapPath(Request.ApplicationPath) + "\\App_GlobalResources\\";

foreach (var file in Directory.EnumerateFiles(dir, "*.resx"))
{
    ddlResources.Items.Add(new ListItem { Text = file.Substring(firstoccuranceof("."), file.LastIndexOf(".")), Value = file });
}

if I do file.Substring(file.IndexOf("."), file.LastIndexOf(".")) I get an error

To answer your actual question - you can use string.IndexOf to get the first occurrence of a character. Note that you'll need to subtract this value from your LastIndexOf call, since Substring 's second parameter is the number of characters to fetch, not a start and end index.

However... Instead of parsing the names, you can just use Path.GetFilenameWithoutExtension to get the filename directly.

First occurence

String.IndexOf('.')

Last occurence

String.LastIndexOf('.')

Use IndexOf and LastIndexOf string methods to get index of first and last occurrence of "search" string. You may use System.IO.Path.GetExtension() , System.IO.Path.GetFileNameWithoutExtension() , and System.IO.Path.GetDirectoryName() methods to parse the path.

For instance,

string file = @"c:\csnet\info.sample.txt";
Console.WriteLine(System.IO.Path.GetDirectoryName(file));           //c:\csnet
Console.WriteLine(System.IO.Path.GetFileName(file));                //info.sample.txt
Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(file));//info.sample
Console.WriteLine(System.IO.Path.GetExtension(file));               //.txt

file.IndexOf(".")

Should get you the first occurence of ".". Otherwise it will return -1 if not found.

I think that in your particular case you are NOT trying to get IndexOf... Instead you need to use 0 because you are trying to create a key based on filename if understand correctly:

`ddlResources.Items.Add(new ListItem(file.Substring(0, file.LastIndexOf(".")), file ));`

Also, you have '{}' in there as in new ListItem { ... } which is also going to cause a syntax error... Anyhow have a look..

Because the original question is marked with the [regex] tag, I'll provide the following solution, however the best answer for simple parsing of paths using .NET is not by regex.

//extracts "filename" from "filename.resx"
string name = Regex.Match("filename.resx", @"^(.*)\..+?$").Groups[1].Value; 

Use an answer that relies on the Path class instead, for simplicity. Other answers contain that info.

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