Saturday, June 7, 2014

Java Program1

Write a Java Program to concatenate all characters at first and sum of numbers at last from the given string. 

For Example: 
Input String ::  azch1234dhrk345
Output: azchdhrk22

Solutions :
1) Using java regex package
2) Using Character class

Solution 1:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SumOfNumbersInString {

   public static void main(String[] args) {
      String myString = "azch1234dhrk345";
      SumOfNumbersInString s = new SumOfNumbersInString();
      System.out.print(s.getResultString(myString));
   }
     
   public String getResultString(String myString){
      Pattern pattern = Pattern.compile("\\d");
      Matcher match = pattern.matcher(myString);
      int sum = 0, index = 0;
      String otherString = "";
      boolean matchFind = false;
      while (match.find()) {
        matchFind = true;
        otherString += myString.substring(index, match.start());
        sum += Integer.parseInt(match.group());
        index = match.end();
      }
      if(index < myString.length()){
        otherString += myString.substring(index);
      }
      if(matchFind){
        return otherString + sum;
      } 
      return myString;
   }
}
// Output : azchdhrk22
 
Solution 2:
//SumOfNumbersInString2.java
public class SumOfNumbersInString2 {
   public static void main(String[] args) {
     String myString = "azch1234dhrk345";
     SumOfNumbersInString2 s = new SumOfNumbersInString2();
     System.out.print(s.getResultString(myString));
   }

   public String getResultString(String myString) {
     StringBuffer sb = new StringBuffer();
     int sum = 0;
     // Iterate over the string from 0th index to length()-1 characters
     // Check for the digit
     // If it is a digit, add this value to sum
     // If it is not digit, append to String Buffer Object
     for (int i = 0; i < myString.length(); i++) {
        char ch = myString.charAt(i);
        if (Character.isDigit(ch)) {
           sum += Character.getNumericValue(ch);
        } else {
           sb.append(ch);
        }
     }
     return sb.toString() + sum;
   }
}
// Output : azchdhrk22

No comments:

Post a Comment