后续词

Subsequence words

假设这是我的 .txt 文件 ABCDBCD,我想使用 .substring 来获取它: ABC BCD CDB DBC BCD

我怎样才能做到这一点?如果一行短于 3 个字符,我也需要停止程序。

static void lesFil(String fil, subsekvens allHashMapSubsequences) throws FileNotFoundException{
    Scanner scanner = new Scanner(new File("File1.txt"));
    String currentLine, subString;

    
    

        while(scanner.hasNextLine()){
            currentLine = scanner.nextLine();
            currentLine = currentLine.trim();

            for (int i = 0; i +  subSize <= currentLine.length(); i++){
    
                subString = currentLinje.substring(i, i + subSize);
                subSekStr.putIfAbsent(subString, new subsequence(subString));
            }
        }
    
   

    scanner.close();

这可能是您需要的

String str = "ABCDBCD";
int substringSize = 3;
String substring;

for(int i=0; i<str.length()-substringSize+1; i++){
  substring = str.substring(i, i+substringSize);
  System.out.println(substring);
}
import java.util.*;

public class Main
{
    public static void main(String[] args) {
        
        String input = "ABCDBCD";
        
        for(int i = 0 ; i < input.length() ; i++) {
                 if(i < input.length() - 2) {
                   String temp = input.substring(i,i+3);
                   System.out.println(temp);
                 }
        }
    }
}

对代码稍作改动:

public static void main(String[] args) throws FileNotFoundException {
    Scanner scanner = new Scanner(new File("C:\Users\Public\File1.txt"));
    String currentLine, subString;
    int subSize = 3;

    while (scanner.hasNextLine()) {
        currentLine = scanner.nextLine();
        currentLine = currentLine.trim();

        if (currentLine.length() < subSize) {
            break;
        }

        for (int i = 0; i + subSize <= currentLine.length(); i++) {

            subString = currentLine.substring(i, i + subSize);
            System.out.print(subString + " ");
        }

        System.out.print("\n");
    }

    scanner.close();
}