Posts

Showing posts with the label java-string-examples

How to check if an input character is a vowel

In this blog post, I will be demonstrating how you can check if an input character is a vowel. I will be using Enum for this. If you’d like to study enums in detail, you can refer to this blog post.   Consider the following code snippet: public enum Vowels {a,e,i,o,u;}public class CheckIfVowel {public static void main(String[] args) {System.out.println("Enter a character:");Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();boolean found = false;for(Vowels vowel:Vowels.values()){if (vowel.name().equalsIgnoreCase(input)){found = true;break;}}if(!found) System.out.println("Input "+input +" is NOT a vowel");else System.out.println("Input "+input +" is a vowel");scanner.close();}} Code explanation First, the code declares an Enum called Vowels . It is assigned the vowels i.e. a,e,i,o,u .  We are using the CheckIfVowel class to check if the input character is a vowel. The input character is read using ...

How to reverse a sentence via Java

In this blog post, I will be demonstrating how you can reverse a sentence via Java. So if the input String is “Hello World”, the program will print “World Hello”.   Consider the following code snippet: package learnjava.strings;public class ReverseASentenceDemo {public static void main(String[] args) {String inputStr = "This is a test program";System.out.println("Input String is "+inputStr);String[] words = inputStr.split(" ");StringBuffer reversedString = new StringBuffer("");for(int i = words.length-1; i >= 0; i --){reversedString.append(words[i]);if(i != 0)reversedString.append(" ");}System.out.println("Reversed String is "+reversedString.toString());}}   In this code, the input String is first split using the String.split method. It is split based on spaces, so it returns an array of words. This array is then traversed in the reverse direction. Each word in the array is appended to a ne...

How to replace a String with another String in Java

In this blog post, I will be demonstrating how you can replace a String with another String via Java. Consider the following code snippet: package learnjava.strings;public class ReplaceStringDemo {public static void main(String[] args) {String str = "Good Morning. Another String with the word Morning.";String newStr= str.replace("Morning", "Night");System.out.println("Original String="+str);System.out.println("new String="+newStr);}}   There is a String.replace method.  It accepts as input the String to be replaced and the value with which it should be replaced. It then replaces each occurrence of the first String with the second String. This method actually accepts   CharSequence  as input.  CharSequence  is an interface. The  String  class implements this interface and so you can pass in a String value to this method. So when you run the code above, it will print the following output to the console: Original String=Good Morning. ...

How to check if a String is a substring of another String

In this blog post, I will be explaining how you can check if a String is a substring of another String. Consider the following code snippet: package learnjava.strings;public class CheckSubstringDemo {public static void main(String[] args) {String strToCheck = "Hello World";String valueToCheck = "Hello";//Method 1 - Use Containsif(strToCheck.contains(valueToCheck))System.out.println(valueToCheck+" is present in "+strToCheck);elseSystem.out.println(valueToCheck+" is NOT present in "+strToCheck);//Method 2 - Use startsWith and indexOfif(strToCheck.startsWith(valueToCheck) || strToCheck.indexOf(valueToCheck) > 0)System.out.println(valueToCheck+" is present in "+strToCheck);elseSystem.out.println(valueToCheck+" is NOT present in "+strToCheck);}}   This code snippet demonstrates two ways to check if a String is a substring of another String. Method 1: This method uses the String.contains method. This returns true if the ...

How to check if a String has digits in Java

In this blog post, I will be explaining how you can check if a String has digits. There are several ways to do this. Consider the following code snippet:   package learnjava.strings;import java.util.regex.Pattern;public class CheckIfStringHasDigits {public static void main(String[] args) {String str = "Hello123";String regex = ".*[0-9].*";//Method 1 - Using String.matchesboolean matches = str.matches( regex );System.out.println("Using String.matches="+matches);//Method 2 - Using pattern.matchesmatches = Pattern.matches( regex , str);System.out.println("Using pattern.matches="+matches);//Method 3 - using pattern.compilematches = Pattern.compile( regex).matcher( str ).find();System.out.println("Using Pattern.compile="+matches);//Method 4 - Checking each characterboolean digitFound = false;char[] characters = str.toCharArray();for(char c:characters){if(Character.isDigit(c)){digitFound = true;break;}}System.out.println("Using manua...

How to split a String via Java

In this blog post, I will be explaining how you can split a String via Java. Consider the following code snippet: package learnjava.strings;public class SplitStringDemo {public static void main(String[] args) {String str = "This is a test String";String[] words = str.split(" ");System.out.println("There are "+words.length+" words");for(String word:words){System.out.println(word);}}} There is a method called String.split . It accepts any regular expression. It splits the String around matches of the specified regular expression. Here, I am simply using a space. This will split the input sentence into words. So if you run the above code, you will get the following output: There are 5 wordsThisisatestString  

How to find the count of each character in a String in Java

In this blog post, I will be demonstrating how you can determine the number of occurrences of each character in a String. Consider the following code snippet: package learnjava.strings;import java.util.HashMap;import java.util.Map;public class CountCharactersDemo {public static void main(String[] args) {String str = "Hello World";Map<Character,Integer> characterCountMap = new HashMap<Character,Integer>(); //map stores each character and its countchar[] charsInStr = str.toCharArray();for(char c:charsInStr){if(characterCountMap.containsKey(c)){ //if the character is already in the map, just increment its countint count = characterCountMap.get(c);count++;characterCountMap.put(c, count);}else{ //if the character is not in the map, add it to the mapcharacterCountMap.put(c, 1);}}for(Character c:characterCountMap.keySet()){System.out.println("Character "+c+" occurs "+characterCountMap.get(c));}}}   The  characterCountMap defines a...

How to convert a String to lowercase in Java

In this blog post, I will be explaining how you can convert a String to lowercase in Java. Consider the following code snippet:   </pre>package learnjava.strings;public class StringLowerCaseDemo {public static void main(String[] args) {String str = "Hello World";str = str.toLowerCase();System.out.println(str);}}<pre>   There is a String.toLowerCase method. This converts the String object on which it is invoked to lowercase and returns the converted String. So when you run the above code, you will get the following output: hello world

How to remove a character from a String via Java

In this blog post, I will be explaining how you can remove a character from a String via Java. Consider the following code snippet: package learnjava.strings;public class RemoveCharacterDemo {public static void main(String[] args) {String str = "Hello World";String modifiedStr = str.replace("l", "");System.out.println(modifiedStr);}}   There is a method String.replace . This replaces the specified character with another character. Here, we are replacing the character ‘l’ with an empty character. So effectively, it is like removing the character “l”. When you run this code, you will get the following output: Heo Word  

How to convert a String to uppercase

In this blog post, I will be explaining how you can convert a String to uppercase. Consider the following code snippet:   package learnjava.strings;public class StringUpperCaseDemo {public static void main(String[] args) {String str = "Hello World";str = str.toUpperCase();System.out.println(str);}}   There is a String.toUpperCase method. This converts the String object on which it is invoked to uppercase and returns the converted String. So when you run the above code, you will get the following output: HELLO WORLD

How to convert a String to a Date

In this blog post, I will be demonstrating how you can convert a String to a Date object. Consider the following code snippet: public class StringToDate {public static void main(String[] args) {System.out.println("Enter a date:");Scanner scanner = new Scanner(System.in);String dateStr = scanner.nextLine();System.out.println("Input date is "+dateStr);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");try {Date date = simpleDateFormat.parse(dateStr);System.out.println("Date in date format is "+date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}scanner.close();}} The input Date in String format is read using the  Scanner  class. The code uses the  SimpleDateFormat class. This is a class that provides date formatting functions. In the constructor, you need to specify the format in which the input date is specified as a String. So in this case, I have specified “ dd-MM-yyyy ” which ...

How to reverse a String in Java

In this post, I will demonstrate how to reverse a String in Java. You can do this in the most obvious way i.e. iterating through the String in the reverse order and creating a new String. The following code snippet demonstrates this:   private static String reverse(String str){String reversedString = &quot;&quot;;for(int i = str.length()-1;i &gt;=0 ; i--){reversedString = reversedString + str.charAt(i);}return reversedString;}   A better way is to use Java’s StringBuilder class that has an in-built reverse method. The following code snippet demonstrates this:   StringBuilder strBuilder = new StringBuilder(str);String reversedString = strBuilder.reverse().toString();  

How to find the number of words in a Sentence

In order to find the number of words in a sentence, you can use the String.split method. The following code demonstrates this:   package demo;public class StringDemo {public static void main(String[] args) {String str = "My first Java program";String[] words = str.split(" ");System.out.println("There are "+words.length+" words");}} So the split method splits the given String on the basis of the space character. It returns a String array with all the words in the input String. You can use any other character to split the String as well. When you run this code, it will print the following on the console: There are 4 words  

How to check if a String has only alphabets

You can use Java regular expressions to check if a String has only alphabets as follows: package demo;public class StringDemo {public static void main(String[] args) {String str = "HelloWorld";String regex = "^[a-zA-Z]+$";boolean matches = str.matches(regex);System.out.println(matches);}}   The above code will print true when you run it. If you change the String str to have any other characters like numbers or special characters, it will print false.

How to replace a character in a String with another character

There is a replace method provided by the String class that can be used to replace a character in a String with another character. The following code snippet demonstrates this:   package demo;public class StringDemo {public static void main(String[] args) {String str = "Hello World";String modifiedStr = str.replace('o', 'i');System.out.println("Modified String is "+modifiedStr);}}     So the above code will replace all occurrences of the letter ‘o’ in the String “Hello World”  an ‘i’ and will print the following: Helli Wirld