Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do get the first occurrence of a char in Substring

Tags:

c#

regex

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

like image 306
ONYX Avatar asked Dec 28 '11 02:12

ONYX


People also ask

How do you find the first occurence of a character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do you find the first occurrence of a word in a string?

To find the index of first occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times. There could be a requirement in your Java application, that you have to find the position of the first occurrence of str2 in str1 .

How do I find the first occurrence of a character in a string in python?

Python3. Method #2 : Using List Slice + index() + list() One can convert the string to list using list() and then using list slicing we reverse the list and use the conventional index method to get the index of first occurrence of element.

How do you find the position of the first occurrence of a substring in a string in python?

Python String find() method returns the lowest index or first occurrence of the substring if it is found in a given string. If it is not found, then it returns -1.


2 Answers

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.

like image 170
Reed Copsey Avatar answered Oct 02 '22 17:10

Reed Copsey


First occurence

String.IndexOf('.')

Last occurence

String.LastIndexOf('.')
like image 44
Tomislav Markovski Avatar answered Oct 02 '22 16:10

Tomislav Markovski