Posts

Showing posts with the label strings

How to convert the given string to number in Java?

 In this tutorial, i am going to explain how to convert a given String to Integer in Java with and without using predefined methods of Java. Input: "1234" Output: 1234 Input: "abc" Output: an Exception. Problem:     How to convert the given string to number in Java? Method 1 - Using predefined method of Integer Class: use ParseInt() method of Integer class to convert given String to Integer. The code snippet is showed below. private static int convertToInteger2(String aString) {                 return Integer.parseInt(aString);      }     Method 2 - Without using predefined methods: In this approach, we are not going to use any predefined methods for conversion. we are going to write our own algorithm for this purpose. The algorithm is simple, we are going to iterate through each character of the give String and convert it to digit. we maintain a tempo...

How to Remove Duplicate White Spaces in String Using Java?

Image
What is White space character in Java? White space is a character which represents space between the words. There are two types of white spaces, those are Horizontal white space, Vertical white space. Horizontal white spaces: These are the white spaces entered through spacebar, Tab keys of the keyboard. Vertical white spaces: These are the white spaces entered through ? Enter key of the keyboard, which results a new line character. Older keyboards such as typewrite keyboards have Return , key meaning "Carriage-Return" ,which is equivalent to new line character. So a white space character in a String can be a space , tab , new line , carriage return , form feed or vertical tab . replaceAll() : Use replaceAll() method of String class to remove white spaces. It's syntax is public String replaceAll(String regex, String replacement) It replaces the portion of the string that matched the given regular expression with the given replacement. To identify the ...

How to get the substring of a given String In Java?

String are most common data types used in any programming languages. In Java String is an Object and is backed by a character array. For example, String str = "abc"; is equivalent to  char val[] = {'a','b','c'}; As String is an object, it has convenient methods to manipulate the contents of String. Remember, Strings are immutable in Java, which means, when ever you perform an action, which requires it's content change, a new String object will be created. Now, lets see which method, we can use to get sub string of the given String. substring() :      substring() method is used to obtain a portion of string between two different positions. The substring() method is overloaded in java, means it has two different method signatures. public String substring(int beginIndex) public String substring(int beginIndex, int endIndex) substring(int beginIndex) :      Use this method, when ever you want a portion of String, from the giv...