Integer To String

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

integer to String :

int i = 42;
String str = Integer.toString(i);
or
String str = "" + i

double to String :
String str = Double.toString(i);

long to String :
String str = Long.toString(l);

float to String :
String str = Float.toString(f);

String to integer :
str = "25";
int i = Integer.valueOf(str).intValue();
or
int i = Integer.parseInt(str);

String to double :
Double d = Double.valueOf(str).doubleValue();

String to long :
long l = Long.valueOf(str).longValue();
or
Long l = Long.parseLong(str);

String to float :
Float f = Float.valueOf(str).floatValue();

decimal to binary :
int i = 42;
String bin = Integer.toBinaryString(i);

decimal to hexadecimal :
int i = 42;
String hexstr = Integer.toString(i, 16);

or
String hexstr = Integer.toHexString(i);

or (with leading zeroes and uppercase)


public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}

hexadecimal (String) to integer :

int i = Integer.valueOf("B8DA3", 16).intValue();


or
int i = Integer.parseInt("B8DA3", 16);

char to String
String s = String.valueOf('c');
integer to ASCII code (byte)
char c = 'A';
int i = (int) c; // i == 65 DECIMAL
To extract Ascii codes from a String
String test = "ABCD";
for ( int i = 0; i < test.length(); ++i ) {
char c = test.charAt( i );
int j = (int) c;
System.out.println(j);
}

integer to boolean
b = (i != 0);
// ex : 42 != 0 --> true

boolean to integer
i = (b)?1:0;
// true --> 1

Note :To catch illegal number conversion, use the try/catch mechanism :
try{
i = Integer.parseInt(aString);
}
catch(NumberFormatException e) {
...
}

Check numeric digit (without check the minus sign)


public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}

Check numeric digit (check the minus sign and decimal seperator)

public static boolean isStringNumeric( String str )


{
DecimalFormatSymbols currentLocaleSymbols = DecimalFormatSymbols.getInstance();
char localeMinusSign = currentLocaleSymbols.getMinusSign();

if ( !Character.isDigit( str.charAt( 0 ) ) && str.charAt( 0 ) != localeMinusSign )


return false;

boolean isDecimalSeparatorFound = false;


char localeDecimalSeparator = currentLocaleSymbols.getDecimalSeparator();

for ( char c : str.substring( 1 ).toCharArray() )


{
if ( !Character.isDigit( c ) )
{
if ( c == localeDecimalSeparator && !isDecimalSeparatorFound )
{
isDecimalSeparatorFound = true;
continue;
}
return false;
}
}
return true;
}

public static boolean isInteger(String s) {


try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
// only got here if we didn't return false
return true;
}

Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation

//check range of character


Pattern p = Pattern.compile("[^A-Za-z0-9]");
if (p.matcher(stringToMatch).find()) {
//...
}

chracter to int ascii


int ascii = (int) character;

int to character ascii


char ascii = (char) integer;

check vowel and consonant


public static boolean isVowel(char c){
String comp = Character.toString(c);
String vowels = "aeiouAEIOU";
return vowels.contains(comp);
}

public static boolean isConsanant(char c){


String comp = Character.toString(c);
String cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
return cons.contains(comp);
}

public class ASCIIUtil {

/**
* Checks whether the supplied character is a letter or number.
*/
public static boolean isLetterOrNumber(int c) {
return isLetter(c) || isNumber(c);
}

/**
* Checks whether the supplied character is a letter.
*/
public static boolean isLetter(int c) {
return isUpperCaseLetter(c) || isLowerCaseLetter(c);
}

/**
* Checks whether the supplied character is an upper-case letter.
*/
public static boolean isUpperCaseLetter(int c) {
return (c >= 65 && c <= 90); // A - Z
}

/**
* Checks whether the supplied character is an lower-case letter.
*/
public static boolean isLowerCaseLetter(int c) {
return (c >= 97 && c <= 122); // a - z
}

/**
* Checks whether the supplied character is a number
*/
public static boolean isNumber(int c) {
return (c >= 48 && c <= 57); // 0 - 9
}
}

trim string

Str.trim();

Method Description
Evaluates if "regex" matches s. Returns only true if the WHOLE string
s.matches("regex")
can be matched.
Creates an array with substrings of s divided at occurrence of "regex".
s.split("regex")
"regex" is not included in the result.
s.replaceFirst("regex"),
Replaces first occurance of "regex" with "replacement.
"replacement"
s.replaceAll("regex"),
Replaces all occurances of "regex" with "replacement.
"replacement"

package de.vogella.regex.string;

public class StringMatcher {


// returns true if the string matches exactly "true"
public boolean isTrue(String s){
return s.matches("true");
}
// returns true if the string matches exactly "true" or "True"
public boolean isTrueVersion2(String s){
return s.matches("[tT]rue");
}
// returns true if the string matches exactly "true" or "True"
// or "yes" or "Yes"
public boolean isTrueOrYes(String s){
return s.matches("[tT]rue|[yY]es");
}
// returns true if the string contains exactly "true"
public boolean containsTrue(String s){
return s.matches(".*true.*");
}
// returns true if the string contains of three letters
public boolean isThreeLetters(String s){
return s.matches("[a-zA-Z]{3}");
// simpler from for
// return s.matches("[a-Z][a-Z][a-Z]");
}
// returns true if the string does not have a number at the beginning
public boolean isNoNumberAtBeginning(String s){
return s.matches("^[^\\d].*");
}
// returns true if the string contains a arbitrary number of characters except b
public boolean isIntersection(String s){
return s.matches("([\\w&&[^b]])*");
}
// returns true if the string contains a number less then 300
public boolean isLessThenThreeHundred(String s){
return s.matches("[^0-9]*[12]?[0-9]{1,2}[^0-9]*");
}

StringTokenizer
StringTokenizer st = new StringTokenizer(str,” “);//” ” separate by anything
while(st.hasMoreTokens()) {
String s = st.nextToken();
}

ArrayList

ArrayList listTest = new ArrayList( );


listTest.size() //size of the array
listTest.add( "first item" ) // add item
listTest.get( 3 ) // get item
listTest.remove(2); // remove by index
listTest.remove( "second item" ); //remove by value

//To go through each item in your ArrayList you can set up something called an
Iterator. This class can also be found in the java.util library:
import java.util.Iterator;

You can then attach your ArrayList to a new Iterator object:

Iterator it = listTest.iterator( );

This sets up a new Iterator object called it that can be used to go through the items
in the ArrayList called listTest. The reason for using an Iterator object is because
it has methods called next and hasNext. You can use these in a loop:

while ( it.hasNext( ) ) {
System.out.println( it.next( ) );
}

LONGGEST COMMON SUBSEQUENCE


public static String lcs(String a, String b) {
int[][] lengths = new int[a.length()+1][b.length()+1];

// row 0 and column 0 are initialized to 0 already

for (int i = 0; i < a.length(); i++)


for (int j = 0; j < b.length(); j++)
if (a.charAt(i) == b.charAt(j))
lengths[i+1][j+1] = lengths[i][j] + 1;
else
lengths[i+1][j+1] =
Math.max(lengths[i+1][j], lengths[i][j+1]);
// read the substring out from the matrix
StringBuffer sb = new StringBuffer();
for (int x = a.length(), y = b.length();
x != 0 && y != 0; ) {
if (lengths[x][y] == lengths[x-1][y])
x--;
else if (lengths[x][y] == lengths[x][y-1])
y--;
else {
assert a.charAt(x-1) == b.charAt(y-1);
sb.append(a.charAt(x-1));
x--;
y--;
}
}

return sb.reverse().toString();
}
Regular Expression (RegEx)
Pattern pattern = Pattern.compile(<REGEX>);
Matcher matcher = patter.matcher(<INPUT ANY STRING>);

Dijkstra

import java.util.InputMismatchException;
import java.util.Scanner;

public class DijkstraShortestPath

{
private boolean settled[];
private boolean unsettled[];
private int distances[];
private int adjacencymatrix[][];
private int numberofvertices;

public DijkstraShortestPath(int numberofvertices)


{
this.numberofvertices = numberofvertices;
this.settled = new boolean[numberofvertices + 1];
this.unsettled = new boolean[numberofvertices + 1];
this.distances = new int[numberofvertices + 1];
this.adjacencymatrix = new int[numberofvertices +
1][numberofvertices + 1];
}
public void dijkstraShortestPath(int source, int adjacencymatrix[][])
{
int evaluationnode;
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
distances[vertex] = Integer.MAX_VALUE;
}
for (int sourcevertex = 1; sourcevertex <= numberofvertices;
sourcevertex++)
{
for (int destinationvertex = 1; destinationvertex <=
numberofvertices; destinationvertex++)
{
this.adjacencymatrix[sourcevertex][destinationvertex]
=
adjacencymatrix[sourcevertex][destinationvertex];
}
}
unsettled[source] = true;
distances[source] = 0;
while (getUnsettledCount(unsettled) != 0)
{
evaluationnode =
getNodeWithMinimumDistanceFromUnsettled(unsettled);
unsettled[evaluationnode] = false;
settled[evaluationnode] = true;
evaluateNeighbours(evaluationnode);
}
}
public int getUnsettledCount(boolean unsettled[])
{
int count = 0;
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
if (unsettled[vertex] == true)
{
count++;
}
}
return count;
}
public int getNodeWithMinimumDistanceFromUnsettled(boolean
unsettled[])
{
int min = Integer.MAX_VALUE;
int node = 0;
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
if (unsettled[vertex] == true && distances[vertex] < min)
{
node = vertex;
min = distances[vertex];
}
}
return node;
}
public void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;

for (int destinationNode = 1; destinationNode <=


numberofvertices; destinationNode++)
{
if (settled[destinationNode] == false)
{
if (adjacencymatrix[evaluationNode][destinationNode] !=
Integer.MAX_VALUE)
{
edgeDistance = adjacencymatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
unsettled[destinationNode] = true;
}
}
}
}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices +
1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the
graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Enter the source ");
source = scan.nextInt();
DijkstraShortestPath dijkstrasAlgorithm = new
DijkstraShortestPath(number_of_vertices);
dijkstrasAlgorithm.dijkstraShortestPath(source,
adjacency_matrix);

System.out.println("The Shorted Path to all nodes are ");


for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1;
i++)
{
System.out.println(source + " to " + i + " is "+
dijkstrasAlgorithm.distances[i]);
}
} catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}
}

Fibonacci

public class Program {

public static int fibonacci(int n) {


int a = 0;
int b = 1;

// Compute Fibonacci sequence.


for (int i = 0; i < n; i++) {
int temp = a;
a = b;
b = temp + b;
}
return a;
}

public static void main(String[] args) {

// Get first 15 Fibonacci numbers.


for (int i = 0; i < 15; i++) {
System.out.println(fibonacci(i));
}
}
}
static int stop = 0;
static int index = 0;
public static void main(String [] args) {
stop = 5;
int num1 =0, num2 = 1;
fib(num1,num2);
}

public static void fib(int num1, int num2) {


System.out.println(num2);
index++;
if(index == stop)
return;

fib(num2,num2+num1);
}

Biginteger

import java.math.BigInteger;
// Create via a string
BigInteger bi1 = new BigInteger("1234567890123456890");

// Create via a long


BigInteger bi2 = BigInteger.valueOf(123L);

bi1 = bi1.add(bi2);
bi1 = bi1.multiply(bi2);
bi1 = bi1.subtract(bi2);
bi1 = bi1.divide(bi2);
bi1 = bi1.mod(bi2);
int exponent = 2;

bi1 = bi1.pow(exponent);
BigInteger bi = new BigInteger("1023");
// Parse and format to binary
bi = new BigInteger("1111111111", 2);
String s = bi.toString(2);

Factorial

public class MainClass {


public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++)
System.out.printf("%d! = %d\n", counter, factorial(counter));

// recursive declaration of method factorial


public static long factorial(long number) {
if (number <= 1) // test for base case
return 1; // base cases: 0! = 1 and 1! = 1
else
// recursion step
return number * factorial(number - 1);
}
}

Permutation

public class MainClass {


public static void main(String args[]) {
permuteString("", "String");
}

public static void permuteString(String beginningString, String


endingString) {
if (endingString.length() <= 1)
System.out.println(beginningString + endingString);
else
for (int i = 0; i < endingString.length(); i++) {
try {
String newString = endingString.substring(0, i) +
endingString.substring(i + 1);

permuteString(beginningString + endingString.charAt(i), newString);


} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
}

Combination

public class Combinations {


private StringBuilder output = new StringBuilder();
private final String inputstring;
public Combinations( final String str ){
inputstring = str;
System.out.println("The input string is : " + inputstring);
}

public static void main (String args[])


{
Combinations combobj= new Combinations("wxyz");
System.out.println("");
System.out.println("");
System.out.println("All possible combinations are : ");
System.out.println("");
System.out.println("");
combobj.combine();
}

public void combine() { combine( 0 ); }


private void combine(int start ){
for( int i = start; i &lt; inputstring.length(); ++i ){
output.append( inputstring.charAt(i) );
System.out.println( output );
if ( i &lt; inputstring.length() )
combine( i + 1);
output.setLength( output.length() - 1 );
}
}
}

Prime number

boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
LinkedList
public class LinkedList {
private Node first; //the 1st node
private Node last; //the last node
private Node current; //if any

public LinkedList(){
first = null; //set the linked list to null
last = null;
current = null;
}

public boolean isEmpty() {


return (first == null);
}
public void insertAtFront(Object insertItem) {
Node newNode = new Node(insertItem); //create new node with value received

if (isEmpty())
{
first = newNode;
last = newNode;
}
else
{
newNode.next = first;
first = newNode;
}
}
public void insertAtBack(Object insertItem)
{
Node newNode = new Node(insertItem);
if(isEmpty())
{
first = newNode;
last = newNode;
}
else
{
last.next = newNode;
last = newNode;
}
}

public Object removeFromFront()


{
Object removeItem = null;

if(isEmpty())
{
return removeItem;
}

removeItem = first.data;
if(first == last)
{
first = null;
last = null;
}
else
first = first.next;

return removeItem;
}

public Object removeFromBack()


{
Object removeItem = null;

if(isEmpty())
{
return removeItem;
}

removeItem = last.data;
if (first == last)
{
first = null;
last = null;
}
else
{
current = first;
while(current.next != last)
current = current.next;
last = current;
last.next = null;
}

return removeItem;
}

public Object getFirst()


{
if(isEmpty())
return null;
else
{
current = first;
return current.data;
}
}
public Object getNext()
{
if(current == last)
return null;
else
{
current = current.next;
return current.data;
}
}

Node

public class Node {


Object data; //data is an object type
Node next; //the pointer points to the next node

Node(Object obj) { //constructor to initialize the first node


data = obj; //just initialize the data, not the reference
link
}
}

Stack
public class Stack
{
private Node first;
private Node last;
private Node current;

public Stack(){
first = null;
last = null;
current = null;
}

public void push(Object insertItem) {


Node newNode = new Node(insertItem);
if(isEmpty()) {
first = newNode;
last = newNode;
}
else {
newNode.next = first;
first = newNode;
}
}

public Object pop() {


Object removeItem = null;

if(isEmpty()) {
return removeItem;
}

removeItem = first.data;
if(first == last) {
first = null;
last = null;
}
else {
first = first.next;
}
return removeItem;
}

public Boolean isEmpty() {


return (first == null);
}

Breadth first search

public class TestProg


{

public static void main(String[] args)


{
// 0 1 2 3 4 5 6 7 8
// ===================================================
int[][] conn = { { 0, 1, 0, 1, 0, 0, 0, 0, 1 }, // 0
{ 1, 0, 0, 0, 0, 0, 0, 1, 0 }, // 1
{ 0, 0, 0, 1, 0, 1, 0, 1, 0 }, // 2
{ 1, 0, 1, 0, 1, 0, 0, 0, 0 }, // 3
{ 0, 0, 0, 1, 0, 0, 0, 0, 1 }, // 4
{ 0, 0, 1, 0, 0, 0, 1, 0, 0 }, // 5
{ 0, 0, 0, 0, 0, 1, 0, 0, 0 }, // 6
{ 0, 1, 1, 0, 0, 0, 0, 0, 0 }, // 7
{ 1, 0, 0, 0, 1, 0, 0, 0, 0 } };// 8

Graph1 G = new Graph1(conn);

G.bfs();

}
}

import java.util.*;

public class Graph1


{
/* ------------------------------------------
Data structure used to represent a graph
------------------------------------------ */
int[][] adjMatrix;
int rootNode = 0;
int NNodes;

boolean[] visited;

/* -------------------------------
Construct a graph of N nodes
------------------------------- */
Graph1(int N)
{
NNodes = N;
adjMatrix = new int[N][N];
visited = new boolean[N];
}

Graph1(int[][] mat)
{
int i, j;

NNodes = mat.length;

adjMatrix = new int[NNodes][NNodes];


visited = new boolean[NNodes];

for ( i=0; i < NNodes; i++)


for ( j=0; j < NNodes; j++)
adjMatrix[i][j] = mat[i][j];
}

public void bfs()


{
// BFS uses Queue data structure

Queue<Integer> q = new LinkedList<Integer>();

q.add(rootNode);
visited[rootNode] = true;

printNode(rootNode);

while( !q.isEmpty() )
{
int n, child;

n = (q.peek()).intValue();

child = getUnvisitedChildNode(n);

if ( child != -1 )
{
visited[child] = true;

printNode(child);

q.add(child);
}
else
{
q.remove();
}
}

clearVisited(); //Clear visited property of nodes


}

int getUnvisitedChildNode(int n)
{
int j;
for ( j = 0; j < NNodes; j++ )
{
if ( adjMatrix[n][j] > 0 )
{
if ( ! visited[j] )
return(j);
}
}

return(-1);
}

void clearVisited()
{
int i;

for (i = 0; i < visited.length; i++)


visited[i] = false;
}

void printNode(int n)
{
System.out.println(n);
}
}

You might also like