Monday 24 July 2017

How to find the String that contains only alphabets

Today we will see how to  find list of Strings that contains only alphabets. In this post I did this with and without using regular expression and using java 8 streams.

package com.interviewCodes.string;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class AlphaString {

       public static void main(String[] args) {

              List<String> strlist = Arrays.asList("abc12#", "abc", "def", "gh$45", "ghi");

              // find the string that contains only alphabets
              System.out.println("List of Strings :: " + strlist);
              System.out.println("Without using reg exp :: " + alphaStrings(strlist));
              System.out.println("Using reg exp :: " + alphaStringsUsingRegExp(strlist));
              System.out.println("Using Java 8 :: "alphaStringsUsingJava8(strlist));

       }

       // Without using REG EXP
       public static List<String> alphaStrings(List<String> list) {
              List<String> alphaStrlist = new ArrayList<>();
              for (String str : list) {
                     char[] chars = str.toCharArray();
                     for (char c : chars) {
                           if (!Character.isLetter(c))
                                  continue;
                           if (str.endsWith(Character.toString(c)))
                                  alphaStrlist.add(str);
                     }
              }
              return alphaStrlist;
       }

       // Using REG EXP
       public static List<String> alphaStringsUsingRegExp(List<String> list) {

              List<String> alphaStrList = new ArrayList<>();
              for (String str : list) {
                     if (str.matches("[a-zA-Z]*$"))
                           alphaStrList.add(str);
              }
              return alphaStrList;
       }

       // Using Java8
      public static List<String> alphaStringsUsingJava8(List<String> list) {
              return list.stream()
                         .filter(i -> i.chars().allMatch(Character::isLetter))
                         .collect(Collectors.toList());
       }

}

Please let me know if there any other better way to do this and also correct me if any mistakes in this post.


Thanks for reading :)

Monday 18 August 2014

How to reverse words in a String

Reverse words in a String


We can reverse  the words in the String by using StirngBuilder as below:

package com.interviewCodes.String;

public class ReverseWordsInString {
      
       public static void main(String args[]){
              String str="Hi I am John";
              System.out.println("Sentence before reverse:"+str);
              System.out.println("Sentence after reversing:"+reverseWords(str));
       }
      
       public static String reverseWords(String sentence){
              StringBuilder sb=new StringBuilder(sentence.length()+1);
              String[] words=sentence.split(" ");
              for(int i=words.length-1;i>=0;i--){
                     sb.append(words[i]).append(' ');
              }
              sb.setLength(sb.length()-1);
              return sb.toString();
       }
}


This is the preferred way to reverse the words in a  String.Please comment the other ways of reversing the words in a String.Thanks for reading.

How to reverse a number in Java

Reverse a number/Integer



We can reverse a number by converting it into a String or iteratively or recursively.
Now we will how to reverse  number by converting it into a String.





package com.interviewCodes.String;

public class ReverseNumberDemo1 {
      
       public static void main(String[] args) {
              int num=12456;
              //converting Integer into a String
              String str=String.valueOf(num);
              //Now we can reverse the String as shown in my previous post
              //And then convert that String into Integer like below
              Integer revNum=Integer.parseInt(str);
       }

}

We can reverse the Number by iteratively or recursively as below:

package com.interviewCodes.String;

import java.util.Scanner;

public class ReverseNumberDemo{

       public static void main(String[] args) {
               
         int num, reverseNum = 0;
      System.out.println("Enter the number to reverse");
      Scanner in = new Scanner(System.in);
      num = in.nextInt();
      //reverse a number iteratively
      reverseNum=reverseIteratievly(num);
      System.out.println("Reverse a number Iteratively : "+reverseNum);
      //reverse a number recursively
      reverseNum=reverseRecursievly(num);
      System.out.println("Reverse a number Iteratively : "+reverseNum);
    }
       public static int reverseIteratievly(int num) {

              int reverse=0;
           while( num != 0 )
             {
                 reverse = reverse * 10;
                 reverse = reverse + num%10;
                 num = num/10;
             }
             return reverse;
       }
    public static int  reverseRecursievly(int num) {
             
       return _reverseRecurievly(num,0);
     }

     public static int _reverseRecurievly(int n,int r){
       if(n==0){
              return r;
       }
       else{
              return _reverseRecurievly(n/10,r*10+n%10);
       }
}

}

That's all about reverse a number.If any other ways are there to reverse a number,please comment.Thanks for reading.

How to reverse String in Java

Reverse String in Java



Hi this is the frequent question that I faced in some of the interviews. So I choose this one to write as my first post.



We can reverse a String using StringBuffer or StringBuilder or without using these two by iteratively or recursively.
First we will see how to reverse a String using StringBuffer and StringBuilder reverse() method.




package com.interviewCodes.String;

public class ReverseStringDemo1 {

       public static void main(String[] args) {

      String orgStr = "Hello World";
      System.out.println("Original String : " + orgStr );
       // reverse a String using StringBuffer
       String revStr = new StringBuffer(orgStr).reverse().toString();
       System.out.println("Reversed String "+ revStr);
       // reverse a String using StringBuilder
       revStr = new StringBuilder(orgStr).reverse().toString();
       System.out.println("Reversed String : "+ revStr);
       }

}

Now we  will how to reverse a String without using StringBuffer and StringBuilder by iteratively or recursively.
package com.interviewCodes.String;

public class ReverseStringDemo2 {

       public static void main(String[] args) {

             String orgnStr = "Hello World";
             System.out.println("Original String : " + orgnStr );
             //reverse a String iteratively
             String revStr = reverse(orgnStr);
             System.out.println("Reversed String "+ revStr);
             //reverse a String recursively
             revStr = reverseRecursively(orgnStr);
             System.out.println("Reversed String "+ revStr);
       } 

       // iterative method to reverse a String
       public static String reverse(String str) {

              if (str == null || str.isEmpty()) {
                     return str;
              }
              String reverse = "";
              for (int i = str.length() - 1; i >= 0; i--) {
                     reverse = reverse + str.charAt(i);
              }
              return reverse;
       }

       // reverse a String recursivly
       public static String reverseRecursively(String str) {

              if (str == null || str.isEmpty() || str.length() < 2) {
                     return str;
              }

              return reverseRecursively(str.substring(1)) + str.charAt(0);

       }
}
     
But I prefered to use StringBuffer or StringBuilder libraries to reverse a String.Please suggest if there are another ways of reversing a String.Thanks for reading.


How to find the String that contains only alphabets

Today we will see how to  find list of Strings that contains only alphabets. In this post I did this with and without using regular expres...