How to get the nth index of the given token occurring in the given string > String search

How to get the nth index of the given token occurring in the given string > String search

Problem Statements:

  1. I have a long String with multiple lines, I want to print last 2 lines from this String.
  2. I want to print second last line from my String.
  3. I want to show only three lines 0f any long string separated by specific character on console.
 Source Code:
 package com;  
 public class Test {  
      /**  
       * @param a  
       */  
      public static void main(String a[]) {  
           String str = "1.Java Technology \n 2.J2EE Technology \n 3.JSP Technology \n 4.Servlet Technology \n 5.Spring Technology \n 6.Hibernate Technology \n 7.Jboss Technology \n 8.Tomcat Technology";  
           System.out.println(" Print String:: \n "+str);  
           System.out.println("\nTotal Number of Lines "+CharCount(str, '\n')+1);  
           //Print Last Two Lines            
           System.out.println("Problem Statement 1 - Print Last Two Lines:: \n"+str.substring(CharIndexOf(str, "\n", 7),str.length()));  
           //Print Second Last Line  
           System.out.println("Problem Statement 2 - Print Second Last Line:: \n"+str.substring(CharIndexOf(str, "\n", 6),str.lastIndexOf("\n")));  
           //Print Last Three Lines  
           System.out.println("Problem Statement 3 - Print Last Three Lines:: \n"+str.substring(CharIndexOf(str, "\n", 6),str.length()));  
      }  
      public static int CharIndexOf(String str, String substr, int n) {  
           int pos = str.indexOf(substr);  
           while (--n > 0 && pos != -1)  
                pos = str.indexOf(substr, pos + 1);  
           return pos;  
      }  
      public static int CharCount(String str, char searchChar) {  
           int count = 0;  
           for( int i=0; i<str.length(); i++ ) {  
             if( str.charAt(i) == searchChar ) {  
               count++;  
             }   
           }  
           return count;  
      }  
 }  
10article.com Tutorials

10article.com Tutorials

Comments

  1. By Sandeep Parbat

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *