计算字符串C#中单词之间的选项卡

时间:2018-01-10 07:12:32

标签: c# delimiter

我需要计算字符串

中单词之间的标签数量
string s = "DATE\t\t\tVERSION\t\tAUTHOR\t\t\t\t\tCOMMENTS";


int TabsDateVersion;     //number of tabs between "Date" and "Version"
int TabsVersionAuthor;   //number of tabs between "Version" and "Author"
int tabsAuthorComments;  //number of tabs between "Author" and "Comments"

注意:单词由一个或多个标签分隔。

知道如何在C#中执行此操作,所以我有3个不同的计数?

4 个答案:

答案 0 :(得分:1)

如果字符串有HAS标签(而不是4个空格代表标签),您可以使用LINQ轻松统计

var s = "DATE,      VERSION             AUTHOR      COMMENTS";

Console.WriteLine(CountTabs(s,"DATE","VERSION"));
Console.WriteLine(CountTabs(s,"VERSION","AUTHOR"));
Console.WriteLine(CountTabs(s,"AUTHOR","COMMENTS"));

public static int CountTabs(string source, string fromVal, string toVal)
{
    int startIdx = source.IndexOf(fromVal);
    int endIdx = source.IndexOf(toVal);

    return source.Skip(startIdx).Take(endIdx - startIdx).Count(c => c == '\t');
}
  

注意:如果fromValtoVal不属于source,则不会进行错误处理。

答案 1 :(得分:1)

使用有关如何在this回答中的单词之间获取文字的信息,我写了一个简单的函数,它将总string,左词,右词和char带到寻找。

public int CountCharactersBetweenWords(string totalString, string leftWord, string rightWord, char search)
{
    // Find the indexes of the end of the left and the start of the right word
    int pFrom = totalString.IndexOf(leftWord) + leftWord.Length;
    int pTo = totalString.LastIndexOf(rightWord);

    // Get the substring between the words
    string between = totalString.Substring(pFrom, pTo - pFrom);

    // Count the characters that are equal with the character to search for
    return between.Count(c => c == search);
}

这样称呼:

string s = "DATE\t\t\tVERSION\t\tAUTHOR\t\t\t\t\tCOMMENTS";
int count = CountCharactersBetweenWords(s, "DATE", "VERSION", '\t');

答案 2 :(得分:1)

按关键字拆分字符串然后计算。

slider.setValue(index, animated: true)

答案 3 :(得分:0)

让我们尝试一个班轮!用正则表达式!

Regex.Match("DATE\t\t\tVERSION\t\tAUTHOR\t\t\t\t\tCOMMENTS", 
    "DATE(\\t*)").Groups[1].Length

这里使用的正则表达式是

DATE(\t*)

它基本上会查找"DATE"并捕获其后的所有制表符并将它们全部放在第1组中。您可以将"DATE"替换为"VERSION""COMMENTS"等。

请记住向System.Text.RegularExpressions添加using指令!