2011-11-11 60 views
0

我有一个名为Function类的功能,如下图所示:发送一个字符串数组作为参数传递给函数

public int SearchedRecords(String [] recs) 
{ 
    int counter = 0; 
    String pat = "-----"; 
    String[] records = recs; 

    foreach (String line in records) 
    { 
     if (line.Contains(pat) == true) 
     { 
      counter++; 
     } 
    } 

    return counter; 
} 

我打电话来,从我的主类这种方法是这样的:

 String [] file = File.ReadAllLines("C:/Users.../results.txt"); 
     int counter = Function.SearchedRecords([]file); 

但我得到一个错误说:

;预计

有什么不对?


另一个问题是:在上述功能从一个文件中的所有行计数与他们的图案-----(即使具有更短划线,或者如果线短划线之前或之后有一些字符)。我对吗?

这就像Java中的模式,所以也许有另一种方式。
你能赐教吗?

+1

'如果(line.Contains(PAT)==真)'可以改为'如果(line.Contains(PAT))'不失去任何意义 –

回答

4

从参数中删除[]。

例如

int counter = Function.SearchedRecords(file); 

是的,你约的行为假设包含方法是正确的 - 你会匹配包含连续五年破折号,任何线路无论是之前或之后他们什么字符。

如果你想解析正好五破折号,没有之前或之后没有什么,我建议看看RegEx类(正则表达式)。

+0

谢谢,但现在我得到一个其他错误..一个对象引用对于非静态字段,方法,por属性是必需的(Function.SearchMethod([]) – tequilaras

+3

这是因为你像一个静态方法那样调用SearchedRecords,但并没有将它声明为一个。代码你需要创建一个新的实例或者定义类似这样的方法:“public static int SearchedRecords(String [] recs)” –

+0

working .. thanks ... – tequilaras

1

将其更改为

int counter = Function.SearchedRecords(file); 
+0

谢谢,但现在我得到了一个其他的错误..一个对象的引用是非静态字段,方法,por属性(Function.SearchMethod([]) – tequilaras

1

从方法调用中删除'[]'。是的,你的功能似乎在计算你想要的。

+0

谢谢,但现在我得到了一个其他错误..一个对象引用是非静态字段,方法,por属性(Function.SearchMethod([])所必需的 – tequilaras

2

变化

int counter = Function.SearchedRecords([]file); 

int counter = Function.SearchedRecords(file); 

,是的,这将工作,对于字符串。 但是,Contains区分大小写,如果您匹配的是名称或具有字母字符的其他字符串,则该案例必须完全相同才能匹配,例如, line.Contains("Binary Worrier")将不匹配一个字符串“Hello hello”。

而且,整个文件读入内存是好的,如果你知道该文件将永远是小,这种方法获取低效率的较大的文件。 最好总是使用类似System.IO.StreamReaderSystem.IO.File.ReadLines(在.Net 4和更高版本中可用),这些允许您一次使用文件一行。例如

using (var reader = new System.IO.StreamReader("MyFile.txt")) 
{ 
    while(!reader.EndOfStream) 
    { 
     string line = reader.ReadLine(); 
     if (line.Contains(pattern)) 
      counter++; 
    } 
} 
1

首先,您需要创建一个函数类的实例,然后运行该函数。希望下面的代码可以帮助

Function fb = new Function(); 
int counter = fb.SearchedRecords(file); 

现在,你正在使用SearchRecords为静态类不需要实例化的静态函数。

1

您可以在更短的方式使用LINQ做到这一点:

int counter = file.Count(line => line.Contains("-----")); 
相关问题