代码之家  ›  专栏  ›  技术社区  ›  rokyo

如何在Java或C++中检查input.txt文件中的大写或小写字母?

  •  0
  • rokyo  · 技术社区  · 7 年前

    我想写一个程序,将.txt文件作为输入,读取它们,并检测文本中字符从大写切换到小写的所有位置。例如,读取输入文件:

    测试输入.txt: Ajhfojojkljklflfjddejhoiojojfojlkmlloisjdo。。。

    我知道,这在普通英语文本中没有意义,因为文本不会经常从大写字母到小写字母变化。然而,我的程序不应该阅读英文文本,而是包含DNA序列的文本,其中基因的所有外显子都用大写字母书写,所有内含子都用小写字母书写。简单来说,我的程序应该以DNA序列作为输入(如.txt文件),然后告诉我外显子与内含子的所有位置。

    在下一步中,程序应该输出并进一步处理第一步中检测到的所有位置的最后三个大写字母和前六个小写字母。因此,对于测试输入。如上图所示,它将输出:

    (技术上含糊不清:剪接供体位点是mRNA转录本的外显子/内含子边缘的九个碱基序列[外显子的最后三个碱基和以下内含子的前六个碱基],其中U1 snRNA结合并启动剪接过程)。

    1 回复  |  直到 7 年前
        1
  •  0
  •   ADWholeMilk    7 年前

    我假设您在Linux环境中,并且您正在命令行终端上使用该程序。

    以下是一个简单的解决方案:

    #include <fstream>
    #include <iostream>
    
    int main (int argc, char **argv) {
      int i, line_size;
      std::ifstream myfile;
      std::string token;
    
      // Check if user put an input file as argument
      if(argc < 2){
        std::cout << "Usage : ./parser filename" << std::endl;
        return 0;
      }
    
      // Open file and check for errors
      myfile.open(argv[1]);
      if(!myfile){
        std::cout << "Error opening file" << std::endl;
        return -1;
      }
    
      // For each line, put the line in variable token
      while(getline(myfile, token)){
        line_size = token.size();
    
        for(i=2; i < line_size - 4; ++i){
          // Go through the line and check for each character if it 
          // is an uppercase character and if the following one is
          // a lowercase character. If so, print it.
          if(std::isupper(token[i]) && std::islower(token[i+1])){
        std::cout << token.substr(i-2, 6) << std::endl;
          }
        }
    
      }
    
      myfile.close();
      return 0;
    }