Advertisement
Leonard_M

getCharAtIndexFromString

May 1st, 2020
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3. import java.util.ArrayList;
  4. import java.util.Scanner;
  5.  
  6. public class main {
  7.  
  8.     public static char getCharAtIndexFromString(ArrayList<String> strings, int index){
  9.         //gaseste char-ul de la indexul dat
  10.         //null daca indexul e mai mare decat lungimea fisierului
  11.  
  12.         int counter = 0;
  13.         Character toReturn = null;
  14.         for (String line : strings) {
  15.             if(counter + line.length() > index){
  16.                 toReturn = line.charAt(index - counter);
  17.             }
  18.             else{
  19.                 counter += line.length();
  20.             }
  21.         }
  22.         return toReturn;
  23.     }
  24.  
  25.     public static void main(String[] args) {
  26.         ArrayList<String> strings = new ArrayList<>();
  27.         try {
  28.             File myObj = new File("filename.txt");
  29.             Scanner myReader = new Scanner(myObj);
  30.             while (myReader.hasNextLine()) {
  31.                 String data = myReader.nextLine();
  32.                 strings.add(data);
  33.             }
  34.             myReader.close();
  35.  
  36.             System.out.println(getCharAtIndexFromString(strings, 12));
  37.         } catch (FileNotFoundException e) {
  38.             System.out.println("An error occurred.");
  39.             e.printStackTrace();
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement