C#String查询它包含的字符数/字符数

时间:2017-03-28 05:37:04

标签: c# string

我想询问字符串中有多少 / 。 当我得到号码时,我现在如何获得所有文件夹(那么如何将它们分开)?

例如:文件夹/猫(1 / = 2个文件夹)String1文件夹,String2 Cats

我首先询问字符串

中是否有 /
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
                    }

字符串示例:

Folder/UnderFolder/Cat/Pics

NewFolder/Cats

Folder

NewFolder

4 个答案:

答案 0 :(得分:4)

要计算/的出现次数,您可以使用Split.Length

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

至于文件夹的名称,您可以通过调用索引

来获取它们
folderString.Split('/')[index]

以下是整个控制台应用代码:

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);

输出结果为:

Folder 
UnderFolder
Cat
Pics
Count: 3

希望它有所帮助!

答案 1 :(得分:1)

你为什么要去正则表达式?查找字符串中的任何字符或拆分字符串非常容易。案例的示例代码:

        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);
        }

答案 2 :(得分:1)

with open(dataset, "r") as f:
    line = f.readline()
    while line != None and line != "":
        arr = line.split(splitter)
        if (len(arr) < 3):
            continue
        user, item, rating = int(arr[0]), int(arr[1]), int(arr[2]) 
        # user,items, ratings are taken from text file
        if (len(train) <= user):
             train.append([])
        train[user].append([item]) # appending to list_of_lists `error here`
        train[user].append([rating]) #`ERROR here

答案 3 :(得分:0)

只需使用标准CreateDirectory方法即可。 Directory.CreateDirectory(@"C:\folder1\folder2\folder3\folder4")