C # String Request for the number / characters it contains

I would like to know how many / are in a line. When I get the number, how can I get all the folders now (so how can I separate them)?


For example: Folder / Cats (1 / = 2 folders) String1 Folder, String2 Cats


I will first ask if the line contains

/
Regex myRegex = new Regex(@"[/]{1}", RegexOptions.IgnoreCase);
                    Match matchSuccess = myRegex.Match(string);
                    if (matchSuccess.Success)
                    {
                        // Create several folders
                        // Folder/Cats....

                    }
                    else
                    {
                        // Create only one folder
                        // Folder
                    }

      


Line examples:

Folder/UnderFolder/Cat/Pics

NewFolder/Cats

Folder

NewFolder

+3


source to share


4 answers


To count the number of occurrences /

, you can useSplit.Length

int count = folderString.Split('/').Length - 1;

      

As for the folder name, you can get them by calling the index

folderString.Split('/')[index]

      

Here's all the console app code for that:



string folderString = @"Folder/UnderFolder/Cat/Pics";
int count = folderString.Split('/').Length - 1;
for(int x = 0; count >= x; x++)
{
    Console.WriteLine(folderString.Split('/')[x]);
}
Console.WriteLine("Count: {0}", count);

      

The output would be:

Folder 
UnderFolder
Cat
Pics
Count: 3

      

Hope it helps!

+4


source


Why do you want to use regex. Finding any characters in a string or splitting a string is very easy. Sample code for your case:



        string input = @"Folder/UnderFolder/Cat/Pics";
        string[] values = input.Split('/');
        int numOfSlashes = values.Length - 1;
        Console.WriteLine("Number of Slashes = " + numOfSlashes);
        foreach (string val in values)
        {
            Console.WriteLine(val);
        }

      

+1


source


        //Your folder path
        string yourFolderPath= @"C:/Folder/UnderFolder/Cat/Pics";
        //If you want to count number of folders in the given folder path
        int FolderCount = yourFolderPath.Count(s => s == '/');
        //If you want to create folder you can use directly below code
        Directory.CreateDirectory(yourFolderPath);

      

+1


source


Just use the standard CreateDirectory . Directory.CreateDirectory(@"C:\folder1\folder2\folder3\folder4")

0


source







All Articles