victorialangoe
victorialangoe

Reputation: 57

Subsequence words

Suppose this is my .txt file ABCDBCD and I want to use .substring to get this: ABC BCD CDB DBC BCD

How can I achieve this? I also need to stop the program if a line is shorter than 3 characters.

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();

Upvotes: 0

Views: 46

Answers (3)

Mehdi Rahimi
Mehdi Rahimi

Reputation: 2566

With a minor changes of your code:

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();
}

Upvotes: 1

Sai Hari Krishnan
Sai Hari Krishnan

Reputation: 41

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);
                 }
        }
    }
}

Upvotes: 0

Rob
Rob

Reputation: 320

This may be what you need

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);
}

Upvotes: 1

Related Questions