我正在寻找文件中的子字符串数量 简而言之,该文件包含一定数量的文章,我需要知道多少。 每篇文章均以:@ARTICLE { 或使用@ARTICLE {(整数系列)
有用的信息: -我要查看10个文件 -没有文件为空 -这段代码给我一个StringIndexOutOfBounds异常
这是我到目前为止的代码:
//To read through all files
for(int i=1; i<=10; i++)
{
try
{
//To look through all the bib files
reader = new Scanner(new FileInputStream("C:/Assg_3-Needed-Files/Latex"+i+".bib"));
System.out.println("Reading Latex"+i+".bib->");
//To read through the whole file
while(reader.hasNextLine())
{
String line = reader.nextLine();
String articles = line.substring(1, 7);
if(line.equals("ARTICLE"))
count+=1;
}
}
catch(FileNotFoundException e)
{
System.err.println("Error opening the file Latex"+i+".bib");
}
}
System.out.print("\n"+count);
答案 0 :(得分:1)
尝试仅在每行上使用String#contains
:
while(reader.hasNextLine()) {
String line = reader.nextLine();
if (line.contains("ARTICLE")) {
count += 1;
}
}
这至少可以解决必须首先使用子字符串的问题。问题在于,尽管匹配的行不应具有超出范围的异常,也不应超过7个字符的行不匹配,但少于7个字符的行会引起问题。
您还可以使用正则表达式模式来确保您将ARTICLE
作为独立单词进行匹配:
while(reader.hasNextLine()) {
String line = reader.nextLine();
if (line.matches("\\bARTICLE\\b")) {
count += 1;
}
}
这将确保您不会计算其中没有articles
之类的行,这并不是您的确切目标。
答案 1 :(得分:0)
您可以检查行是否以所需的顺序开头:
params = {
'TableName': 'Test',
'KeyConditions': {
"flight": {
'ComparisonOperator': "EQ",
'AttributeValueList': [{'S': '2002'}]
}
}
}
答案 2 :(得分:0)
您将从以下代码行获取StringIndexOutOfBounds:
String articles = line.substring(1, 7);
读入的行可以为空或少于7个字符。为避免获取StringIndexOutOfBounds,您应该进行条件检查以查看
line.length> 7
除此之外,最好使用上面建议的答案(即 .contains 或 .startsWith )
答案 3 :(得分:0)
由于您正在逐行阅读,因此string.contains是一个不错的选择,而不是子字符串,另一方面,所有文章均以“ @ ARTICLE” 开头,因此请使用“ @ ARTICLE “ 。对于代码测试,请尝试此-
for (float current_time = 0; current_time < max_time; current_time += time_step)
{
clEnqueueNDRangeKernel(queue, kernel1, ...);
clEnqueueNDRangeKernel(queue, kernel2, ...);
clEnqueueNDRangeKernel(queue, kernel3, ...);
}