String – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Fri, 28 Oct 2022 09:34:23 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 String – Java2Blog https://java2blog.com 32 32 Convert UUID to String in Java https://java2blog.com/convert-uuid-to-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=convert-uuid-to-string-java https://java2blog.com/convert-uuid-to-string-java/#respond Fri, 28 Oct 2022 09:34:23 +0000 https://java2blog.com/?p=20949 Introduction

In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look at UUID.

UUID: UUID stands for Universally Unique Identifier which identifies a unique entity or resource in the computer systems. This resource can be a document, real-time object, file, and more. It is also known by the name GUID or Globally Unique Identifier for its extensive use.

It is a value of size 128 bits composed of 32 hexadecimal-based characters and 6 ‘-‘ i.e. hyphens that account for its total length of 36 characters. In programming, we generally represent this type of data as a String.

Example of a UUID: 123e4567-e89b-12d3-a456-426614174000

UUID follows universal standards set by the Internet Society to ensure the uniqueness of every resource that has a UUID.

Uses:

  • The Uniqueness of UUIDs makes them useful for being Associative keys in database tables.
  • They are also used as Identifiers for physical hardware within an organization.
  • They have applications in Cryptography and other hashing utilities.

UUID class in Java

With the advent of Java 7, the UUID class was introduced in Java which packed the different specifications and utilities of UUID into a single unit with some useful methods as well.

We can generate a random UUID or we can generate the UUID from an input String as well. We can generate it as a UUID object or convert it to a string as well. If we can convert a UUID to a String, then we can format and perform the same operations with the utility methods that are possible on a String.

Let us look at how we can generate UUIDs and print them:

import java.util.UUID;  

public class Java2Blog  
{ 
	
	public static void main(String[] args)   
	{  
		UUID uuid=UUID.randomUUID(); //Generates random UUID  
		System.out.println(uuid);  
	}  
}

Output:

Convert UUID to String in Java

We can print a UUID object directly or use the String representation of the UUID object. With the toString() method we can convert a UUID to its equivalent String representation. We can change the object type but the representation remains the same.

We will discuss two different examples where we generate a random UUID and another from a given string. Then we convert them to String using the toString() method.

Let us look at the code snippet for the two approaches.

import java.util.UUID;  

public class Java2Blog  
{ 
	
	public static void main(String[] args)   
	{  
		UUID uuid=UUID.randomUUID(); //Generates random UUID  
		
		String str = uuid.toString();
		
		System.out.println("String representation of Random generated UUID is :");  
		System.out.println();
		System.out.println(str);
	}  
}

Output:

Next, In the below example, we generate UUID from an input string using the fromString() method of the UUID class.

import java.util.UUID;  

public class Java2Blog  
{ 
	
	public static void main(String[] args)   
	{  
		UUID uuid=UUID.fromString("8745d341-966f-4b47-a313-0c5b0795e1bb"); //Generates random UUID  
		
		String str = uuid.toString();
		
		System.out.println("String representation of an Input generated UUID is :");  
		System.out.println();
		System.out.println(str);
	}  
}

Output:

That’s all for the article, we had a brief look at the UUID’s concept, and a brief look at its Java class. Along with this, we had a look at How to Convert a UUID to a String and its representation. You can try out the above examples in your local Java compiler/IDE.

Feel free to reach out to us for any suggestions/doubts.

]]>
https://java2blog.com/convert-uuid-to-string-java/feed/ 0
Repeat String N times in Java https://java2blog.com/repeat-string-n-times-java/?utm_source=rss&utm_medium=rss&utm_campaign=repeat-string-n-times-java https://java2blog.com/repeat-string-n-times-java/#respond Mon, 26 Sep 2022 18:46:47 +0000 https://java2blog.com/?p=20641 Introduction

In this article, we will learn how to Repeat a given String N times in Java . This is a trick question common in JAVA interviews and the candidate’s evaluation is based on different approaches he/she provides for the problem.

So we will take a deep dive into looking at various ways to solve this problem, starting from the simplest approach to digging deep into how many approaches to ace our concepts. Let us first look at a quick glimpse of Strings in Java.

What is a String in Java?

String in general is a sequence of characters. In Java, String can be represented as an Object and a Literal. Using the String Object we can use the common utility methods provided by the String Class. Let us look at the syntax of declaring a String.

String as an object :

String str = new String("Welcome To Java2Blog");

String as a literal or variable :

String str = Welcome To Java2Blog";

Note: We can also use the standard utility methods of the String Class with String literals, but the modifications will not reflect in the actual variable. This explains the Immutability of String in Java.

Repeat String N times in Java

Now, without further ado let us outline different ways to solve this problem and explain each method in detail with examples.

Simple For Loop to Repeat String N Times in Java

We can repeat String N times using a for loop in java. This is an iterative way to solve this problem. There are some points to note:

  • We take the input string str and a variable string result which will contain the resultant string.
  • We will run a loop N times that is given as input.
  • On each iteration we will concatenate the result string with the given string like this: result = result + str

In this way, we will have our resultant string repeated N times. Let us understand this with a code snippet.

public class Java2Blog {

   static String repeatString(String str, int n)
   {
       if(str == null || str == "" )
           return str;              // Return the String if it is empty or null.

       String result = "";          // Empty String which will hold The Resultant String Repeated N times      
       for ( int i=0;i<n;i++)        // Loop N times
       {
           result = result + str;
       }

       return result;
   }

   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 3;              

        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times is : ");
        System.out.println(result);

   }
}

Output:

Using Recursion to Repeat String N Times in Java

Given that we have to repeat a String that involves repeating a process over and over again, we can surmise that Recursion will be helpful to solve this problem. Important points to note:

  • If the input String is null or the counter N = 0, we simply return the string.
  • Otherwise, we return the input string and concatenate it with the value returned by the recursive call.
  • While making each recursive call we decrease the counter N to reach the base condition.

Let us look at the code snippet.

public class Java2Blog {

   static String repeatString(String str, int n)
   {
       // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       else 
       {
           n--;
           return str + repeatString(str,n);
       }

   }

   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 4;              

        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using Recursion is : \n");

        System.out.println(result);

   }
}

Output:

String.format() method to Repeat String N Times in Java

The String class in Java has some very useful methods to represent a String in various ways. The format() method of the String class is a method that returns a String in a specific format provided in the arguments. The syntax of the method is :

public static String format(String format, Object... args)

Important points to note:

  • In the format() method we pass the String as a text to format a number 0 to repeat N times.
  • We provide the parameter as ‘0’ to which we convert it to repeat N times.
  • Then, we replace the formatted string with the original string.

Let us look at the code implementation.

public class Java2Blog {
    
   static String repeatString(String str, int n)
   {
       // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       // string.format repeats a number zero 6 times.
       // then we replace number 0 with original string str to repeat 6 times.
       String result = String.format("%0" + n + "d",0).replace("0", str);
           
       return result;
   }
 
   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 6;              
        
        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using String.fomrat is : \n");
        
        System.out.println(result);
        
   }
}

Output:

Using String.repeat() method in Java 11 to Repeat String N Times

With the introduction of Java 11, a new utility method was added to the String class -> repeat() method. With the repeat() method in the picture, we could repeat any String just by calling the method with the String variable name.

It takes only positive integer values as a parameter and returns a String that is repeated the specified times. The method throws IllegalArgumentException if the count is negative.

Syntax of the method:

public String repeat(int count)

Note: JDK 11.0 or higher must be installed on your machine to use this API.

public class Java2Blog {
    
   static String repeatString(String str, int n)
   {
       // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       
       String result = str.repeat(n);
           
       return result;
   }
 
   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 3;              
        
        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using String.repeat() is : \n");
        
        System.out.println(result);
        
   }
}

Output:

Regular Expression – Regex to Repeat String N Times in Java

In Java, with the String replace() method we can define a Regular expression or a regex to modify any String.

Important Points to note:

  • We will create a String using a character or char array of length N, that is the number of times we want the String to repeat.
  • Next, we will replace each value in the array with the input String.
  • Since the default value of each element in the char array is null we replace ‘\0’ with our input String.

Let us have a look at the code snippet.

public class Java2Blog {
    
   static String repeatString(String str, int n)
   {
       // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       //  creating char array of size n and then replace each value with str
       String result = new String(new char[n]).replace("\0", str);
       
       return result;
		
   }
 
   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 7;              
        
        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using String regex is : \n");
        
        System.out.println(result);
        
   }
}

Output:

Collections.nCopies() method to Repeat String N Times in Java

With the advent of Java 8, the Collection Framework was introduced in java. Along with this, the Collections class was introduced that provided static methods to operate on the Collection and return the collection.

The nCopies() method of the Collections class generates n number of copies of any object type. It accepts two parameters: n -> the number of copies to make and the object to copy.

The syntax of the method:

public static <T> List<T> nCopies(int n, T o)

T is the generic type. Ex: String, Object, etc.

Important Points to note:

  • The nCopies() method returns an Immutable list of objects. We pass the String to make copies of it.
  • After this we join each element in the returned list using the String.join() method.
  • We pass "" empty braces as the delimiter to the join() method so the repeats consecutively.

Let us look at the code implementation for this.

import java.util.Collections;
public class Java2Blog {
    
   static String repeatString(String str, int n)
   {
	   // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       // first make copies
       // then join list elements using empty braces delimiter.
       String result = String.join("",Collections.nCopies(n, str));
       
       return result;
		
   }
 
   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 5;              
        
        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using Collections is : \n");
        
        System.out.println(result);
        
   }
}

Output:

Using Stream API to Repeat String N Times in Java

In Java 8, the introduction of the Stream API and Lambda expressions helped in minimizing the code and add more features of functional programming.

Important points to note:

  • We use the Stream.generate() method as a Lambda expression and pass the input string as a parameter to generate copies of it. We use the limit() method to limit the number of copies to generate.
  • We use the collect() method to collect all the copies of the string.
  • To join them use the joining() method of the Collectors class inside the collect() method.

Let us look at the code snippet.

import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java2Blog {
    
   static String repeatString(String str, int n)
   {
       // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       // first make copies using generate
       // then join them using collect method
       String result = Stream.generate(() -> str).limit(n).collect(Collectors.joining());
       
       return result;
		
   }
 
   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 6;              
        
        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using Stream API is : \n");
        
        System.out.println(result);
        
   }
}

Output:

StringUtils Package – Apache Commons Library to Repeat String N Times in Java

The Apache Commons API provides powerful and reusable Java components and dependencies that we can embed into our applications and programs. Here, to repeat a String N times we can use the inbuilt functionality of this package.

We can use the StringUtils class of the Apache Commons Library by importing with the following dependency. For our ease, we will use the JAR file component of the Apache Commons Lang package.

To set up the JAR file component for this package we follow the steps mentioned here.

After this, we can just use the import statement to embed the StringUtils class from the Apache Commons Lang package. The StringUtils class provides the repeat() method as well to repeat a particular input String as we saw in earlier examples.

Let us look at the code for this as well.

import org.apache.commons.lang3.StringUtils;
public class Java2Blog {
    
   static String repeatString(String str, int n)
   {
	   // Return the String if it is null or if n = 0.
       if(str == null || n <= 0)
            return "";
       // use the repeat method
       String result = StringUtils.repeat(str,n);
       
       return result;
		
   }
 
   public static void main(String args[])
   {
        String str = "Java2Blog";
        int numberOfTimes = 8;              
        
        String result = repeatString(str,numberOfTimes);
        System.out.println("The String Repeated "+numberOfTimes+" times using StringUtils Class is : \n");
        
        System.out.println(result);
        
   }
}

Output:

That’s all for the post, we took a deep dive into various methods that one can use to Repeat a String N Times in Java. We had a look at different examples with the code. You can try these examples out at your local Java IDE.

Feel free to reach out for any suggestions/doubts.

]]>
https://java2blog.com/repeat-string-n-times-java/feed/ 0
How to Replace Space with Underscore in Java https://java2blog.com/replace-space-with-underscore-java/?utm_source=rss&utm_medium=rss&utm_campaign=replace-space-with-underscore-java https://java2blog.com/replace-space-with-underscore-java/#respond Thu, 15 Sep 2022 18:17:24 +0000 https://java2blog.com/?p=20512 Learn about how to replace space with underscore in java.

Replace space with underscore in java

1. Using replace() method

Use String’s replace() method to replace space with underscore in java.

String’s replace() method returns a string replacing all the CharSequence to CharSequence.
Syntax of replace() method:

public String replace(CharSequence target, CharSequence replacement)
package org.arpit.java2blog;

public class ReplaceSpaceWithUnderscoreMain {

    public static void main(String[] args) {
        String str = "This blog is Java2blog";
        str = str.replace(" ","_");
        System.out.println(str);
    }
}

Output:

This_blog_is_Java2blog

As you can see, replace() method replaceed each space with underscore.

2. Using replaceAll() method

Use replaceAll() method to replace space with underscore in java. It is identical to replace() method, but it takes regex as argument. You can go through difference between replace and replaceAll over here.

Here is syntax of replaceAll method:

public String replaceAll(String regex, String replacement)
package org.arpit.java2blog;

public class ReplaceSpaceWithUnderscoreMain {
    public static void main(String[] args) {
        String str = "This blog is Java2blog";
        str = str.replaceAll(" ","_");
        System.out.println(str);
    }
}

Output:

This_blog_is_Java2blog

If you want to replace consecutive spaces with one underscore, you can use replaceAll with regex \\s+.

package org.arpit.java2blog;

public class ReplaceMultipleSpacesWithUnderscoreMain {

    public static void main(String[] args) {
        String str = "  This    blog    is     Java2blog  ";
        str = str.replaceAll("\\s+","_");
        System.out.println(str);
    }
}

Output:

_This_blog_is_Java2blog_

If you don’t want first and last underscore in the output, call trim() method before calling repalceAll() method.

package org.arpit.java2blog;

public class ReplaceMultipleSpacesWithUnderscoreMain {

    public static void main(String[] args) {
        String str = "  This    blog    is     Java2blog  ";
        str = str.trim().replaceAll("\\s+","_");
        System.out.println(str);
    }
}

Output:

This_blog_is_Java2blog

That’s all about how to replace space with underscore in java.

]]>
https://java2blog.com/replace-space-with-underscore-java/feed/ 0
How to Replace Comma with Space in Java https://java2blog.com/replace-comma-with-space-java/?utm_source=rss&utm_medium=rss&utm_campaign=replace-comma-with-space-java https://java2blog.com/replace-comma-with-space-java/#respond Thu, 15 Sep 2022 17:51:48 +0000 https://java2blog.com/?p=20505 Learn about how to replace comma with space in java.

Replace comma with space in java

1. Using replace() method

Use String’s replace() method to replace comma with space in java.

Here is syntax of replace() method:

public String replace(CharSequence target, CharSequence replacement)
package org.arpit.java2blog;

public class ReplaceCommaWithSpaceMain {

    public static void main(String[] args) {
        String str = "1,2,3,4";
        str = str.replace(","," ");
        System.out.println(str);
    }
}

Output:

1 2 3 4

As you can see, replace() method replaced each comma with space in the String.

2. Using replaceAll() method

Use replaceAll() method to replace comma with space in java. It is identical to replace() method, but it takes regex as argument. You can go through difference between replace and replaceAll over here.

Here is syntax of replaceAll method:

public String replaceAll(String regex, String replacement)
package org.arpit.java2blog;

public class ReplaceCommaWithSpaceMain {
    public static void main(String[] args) {
        String str = "1,2,3,4";
        str = str.replaceAll(","," ");
        System.out.println(str);
    }
}

Output:

1 2 3 4

That’s all about how to replace comma with space in java.

]]>
https://java2blog.com/replace-comma-with-space-java/feed/ 0
Remove Parentheses From String in Java https://java2blog.com/remove-parentheses-from-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=remove-parentheses-from-string-java https://java2blog.com/remove-parentheses-from-string-java/#respond Sat, 11 Jun 2022 11:11:57 +0000 https://java2blog.com/?p=20232 Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java.

Java Strings

Java Strings is a class that stores the text data at contiguous memory locations. The String class implements the CharSequence interface along with other interfaces.

Strings are a constant data structure and hence their values can not be changed once created.

However, there are several methods implemented within the class that makes working with Java Strings easier and more robust.

There are two ways in which you can remove the parentheses from a String in Java.

  • You can traverse the whole string and append the characters other than parentheses to the new String.
  • You can use the replaceAll() method of the String class to remove all the occurrences of parentheses.

Let us see each one of them separately.

Remove Parentheses From a String Using the replaceAll() Method

Yet another method to remove the parentheses from the Java String is to invoke the replaceAll() method.

The replaceAll() method is a method of the String class. You can invoke the method on an instance of the String class.

Let us see the definition of the method.

public String replaceAll(String regex,
                String replacement)
  • The method accepts two arguments.
    • String regex: This argument is a regular expression. You shall input a regular expression to the method. The method checks the passed regex within the original string.
    • Regular expressions are a set of characters that represent a pattern in a text.
    • String replacement: This argument represents the string that will be inserted in the place of the matched pattern.

For example, let us say you have a string “{a}[b(c)d]”. In order to replace the parentheses, you shall pass a regular expression (“[\[\](){}]”) and the empty string ‘replacement’.

This will replace all the parentheses with a blank string. In essence, the parentheses will be removed.

You can read more about regex here.

Note that the replaceAll() method returns a string. Therefore, you must reassign the returned string to the original string in order to reflect the changes in the original string.

Let us see the code.

package java2blog;

public class parRemove 
{
    public static void main(String [] args)
    {
        String str = "{a}[b(c)d]";
        str = str.replaceAll("[\\[\\](){}]", "");
        System.out.println("New string is: "+str);
    }
}

Output:

New string is: abcd

Remove Parentheses From a String by Traversing

The idea behind removing the parentheses using this method is simple. You can traverse the String using a loop and pick characters only if they are not parentheses.

You can follow the steps given below to perform the aforementioned task.

  • Take a temporary empty string.
  • Traverse through the string using a loop.
  • Extract the characters from the string one at a time using the index.
  • Check if the current character is a parenthesis using the comparison operator (==).
    • If yes, simply ignore the character.
    • Otherwise, append the character to a temporary string.
  • After the loop completes, copy the temporary string to the original string.

Note that you can not directly fetch the character from a Java String using the index inside the square brackets. For that purpose, you need to invoke the charAt() method by passing the index to it.

The definition of the charAt() method is given below.

public char charAt(int index)

The method returns the character at the respective index.

To append the character, you can directly use the concatenation operator (+).

Let us see the code.

package java2blog;

public class parRemove 
{
    public static void main(String [] args)
    {
        String str = "{a}[b(c)d]";
        String temp="";
        for(int i=0;i

Note that you need to reassign the string to itself after concatenation because the Java Strings are immutable and you can not make changes in place.

Also, note the length() method. It returns the number of characters in the string.

Output:

The new string is: abcd

Conclusion

The replaceAll() method to remove the occurrence of parentheses is more robust as well as simple in terms of complexities.

This is all about removing the parentheses from a string in Java.

Hope you enjoyed reading the article. Stay tuned for more such articles. Happy Learning!

]]> https://java2blog.com/remove-parentheses-from-string-java/feed/ 0 Escape percent sign in String’s format method in java https://java2blog.com/escape-percent-sign-string-format-java/?utm_source=rss&utm_medium=rss&utm_campaign=escape-percent-sign-string-format-java https://java2blog.com/escape-percent-sign-string-format-java/#respond Tue, 08 Feb 2022 18:18:40 +0000 https://java2blog.com/?p=19290 In this post, we will see how to escape Percent sign in String’s format() method in java.

Escape Percent Sign in String’s Format Method in Java

String’s format() method uses percent sign(%) as prefix of format specifier.
For example:
To use number in String’s format() method, we use %d, but what if you actually want to use percent sign in the String.

If you want to escape percent sign in String’s format method, you can use % twice (%%).

Let’s see with the help of example:

package org.arpit.java2blog;

public class EscapePercentSignStringFormat {

    public static void main(String[] args) {
        String percentSignStr = String.format("10 out of 100 is %d%%", 10);
        System.out.println(percentSignStr);
    }
}

Output:

10 out of 100 is 10%

As you can see, we have used %% to escape percent symbol in 10%.

Escape Percent Sign in printf() Method in Java

You can apply same logic in printf method to print percent sign using System.out.printf() method.

package org.arpit.java2blog;

public class EscapePercentSignStringFormat {

    public static void main(String[] args) {
        System.out.printf("10 out of 100 is %d%%", 10);
    }
}

Output:

10 out of 100 is 10%

That’s all about How to escape percent sign in String’s format method in java.

]]>
https://java2blog.com/escape-percent-sign-string-format-java/feed/ 0
Get Unicode Value of Character in Java https://java2blog.com/get-unicode-value-of-character-java/?utm_source=rss&utm_medium=rss&utm_campaign=get-unicode-value-of-character-java https://java2blog.com/get-unicode-value-of-character-java/#respond Mon, 07 Feb 2022 13:03:52 +0000 https://java2blog.com/?p=19227 In this post, we will see how to get unicode value of character in java.

Get Unicode Value of Character in Java

You can simply use below code to get unicode value of character in java.

private static String getUnicodeCharacterOfChar(char ch) {
    return String.format("\\u%04x", (int) ch);
}

Here is complete example to print unicode value of character in java:

package org.arpit.java2blog;

public class GetUnicodeCharacterOfCharMain {

    public static void main(String[] args) {

        String str="java2blog";
        String char1 = getUnicodeCharacterOfChar(str.charAt(3));
        System.out.println("Unicode value of character d: "+char1);

        String char2 = getUnicodeCharacterOfChar('क');
        System.out.println("Unicode value of character क: "+char2);
    }

    private static String getUnicodeCharacterOfChar(char ch) {
        return String.format("\\u%04x", (int) ch);
    }
}

Output

Unicode value of character d: \u0061
Unicode value of character क: \u0915

If source is not character but string, you must chatAt(index) to get unicode value of the character.

package org.arpit.java2blog;

public class GetUnicodeValueOfCharMain {

    public static void main(String[] args) {

        String str="java2blog";
        String char1 = getUnicodeCharacterOfChar(str.charAt(3));
        System.out.println("Unicode value of character d: "+char1);

    }

    private static String getUnicodeCharacterOfChar(char ch) {
        return String.format("\\u%04x", (int) ch);
    }
}

Output:

Unicode value of character d: \u0061

Get Unicode Character Code in Java

In java, char is a "16 bit integer", you can simply cast char to int and get code of unicode character.

char char1 = 'ज';
int code = (int) char1;

Here is definition of char from Oracle:

The char data type is a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).

Here is complete example:

package org.arpit.java2blog;

public class GetUnicodeCodeOfCharMain {

    public static void main(String[] args) {

        char char1 = '®';
        System.out.println(String.format("Unicode character code: %d", (int) char1));
        System.out.println(String.format("Unicode character code in hexa format: %x", (int) char1));
    }
}
Unicode character code: 174
Unicode character code in hexa format: ae

That’s all about how to get unicode value of character in java.

]]>
https://java2blog.com/get-unicode-value-of-character-java/feed/ 0
Find Character in String in Java https://java2blog.com/find-character-in-string-java/?utm_source=rss&utm_medium=rss&utm_campaign=find-character-in-string-java https://java2blog.com/find-character-in-string-java/#respond Wed, 02 Feb 2022 18:23:20 +0000 https://java2blog.com/?p=19181 In this post, we will see how to find character in String in java.

How to Find Character in String in Java

There are multiple ways to find char in String in java

1. Using indexOf() Method to Find Character in String in Java

indexOf() method is used to find index of substring present in String. It returns 1 if character is present in String else returns -1.

public int indexOf(int ch)

Let’s see with the help of example:

package org.arpit.java2blog;

public class FindCharacterInStringJava {

    public static void main(String[] args) {
        String str =  "Java2blog";
        int indexOfA = str.indexOf('a');
        System.out.println("Index of a in String Java2blog is: "+indexOfA);
    }
}

Output:

Index of a in String Java2blog is: 1

In case, you want to find character in String after nth index, then you can pass fromIndex to indexOf method.

int indexOfA = str.indexOf('a',3);
 // Output : 5

2. Using lastIndexOf() Method to Find Char in String in Java

lastIndexOf() method is used to find last index of substring present in String. It returns 1 if character is present in String else returns -1. This method scans String from end and returns as soon as it finds the character.

public int lastIndexOf(int ch)
package org.arpit.java2blog;

public class FindCharacterInStringJava {

    public static void main(String[] args) {
        String str =  "Java2blog";
        int indexOfA = str.lastIndexOf('a');
        System.out.println("Index of a in String Java2blog is: "+indexOfA);
    }
}

Output:

Index of a in String Java2blog is: 3

Find Character at Index in String in Java

Using String’s charAt() method, you can find character at index in String in java.

public char charAt(int index)

Let’s see with the help of example:

package org.arpit.java2blog;

public class FindCharacterInStringJava {

    public static void main(String[] args) {
        String str =  "Java2blog";
        char charAtIndex5 = str.charAt(5);
        System.out.println("Character at index 5 in String Java2blog is: "+charAtIndex5);
    }
}

Output:

Character at index 5 in String Java2blog is: b

how Do I Find Word in String in Java?

You can use indexOf() method to find word in String in java. You need to pass word to indexOf() method and it will return the index of word in the String.

package org.arpit.java2blog;

public class FindWordInStringMain {

    public static void main(String[] args) {
        String str =  "Java2blog";
        int indexOfA = str.indexOf("blog");
        System.out.println("Index of blog in String Java2blog is: "+indexOfA);
    }
}

Output:

Index of a in String Java2blog is: 5

That’s all about how to find character in String in java.

]]>
https://java2blog.com/find-character-in-string-java/feed/ 0
Remove substring from String in Java https://java2blog.com/remove-substring-from-string-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=remove-substring-from-string-in-java https://java2blog.com/remove-substring-from-string-in-java/#respond Tue, 13 Jul 2021 14:33:43 +0000 https://java2blog.com/?p=15603 In this post, we will see how to remove substring from String in java.

There are multiple ways to remove substring from String in java.

Using String’s replace method to remove substring from String in Java

This method belongs to the Java String class and is overloaded to provide two different implementations of the same method.

The first method introduces a new character to a string that is used to replace all the old characters in that string.

After all the old characters are replaced, the method returns the string with the new characters.

If the new character is not found in the string, the method returns this string.

public class RemoveSubStringString
{
    public static void main(String[] args) {

        String description = "mesquite in your cellar";
        String replace = description.replace('e', 'o');
        System.out.println(replace);
    }
}

Output:

mosquito in your collar

The second method replaces a CharSequence which is simply a sequence of characters with the desired sequence of characters from a string.

This method works the same way as the first method, only that it replaces a sequence of characters.

public class RemoveSubStringString
{
    public static void main(String[] arg){
        String fruit = "Mary likes apples";
        String replace = fruit.replace("apples", "mangoes");
        System.out.println(replace);
    }
}

Output:

Mary likes mangoes

If you want to remove substring from the String in java, you can simply replace the substring with empty String.

Here is an example:

package org.arpit.java2blog;

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String fruit = "Mary likes apples";
        String replace = fruit.replace("apples", "");
        System.out.println(replace);
    }
}

Output:

Mary likes

Using String’s replaceFirst method to remove substring from String in Java

This method uses a regular expression to identify a string that matches the regular expression and is replaced with the passed string if present.

This method uses compile() and matcher() methods from the Pattern class behind the scenes to extract the string using the regular expression.

The method returns a string, and if the regular expression is invalid, the method throws a PatternSyntaxException error.

We will create a regular expression that extracts a number from a string and replaces it with another number as a string.

Note that this number will only replace the first two numbers in the string, and the other numbers will not be altered.

package org.arpit.java2blog;

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String age = "Peter is 29 years old, and Jane is 60 years old";
        String replaceFirst = age.replaceFirst("\\d\\d", "30");
        System.out.println(replaceFirst);
    }
}

Output:

Peter is 30 years old and Jane is 60 years old

If you want to remove substring from String, you can use empty String with replaceFirst() method

Here is an example:

package org.arpit.java2blog.entry;

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String age = "Peter is 29 years old, and Jane is 60 years old";
        String replaceFirst = age.replaceFirst("\\d\\d", "");
        System.out.println(replaceFirst);
    }
}

Output:

Peter is years old, and Jane is 60 years old

Using String’s replaceAll method to remove substring from String in Java

Unlike thereplaceFirst, thereplaceAll method uses the regular expression to replace all the occurrences in the string.

Similar toreplaceFirst, This method uses compile() and matcher() methods to extract a string using a regular expression and also throws a PatternSyntaxException when the regular expression is invalid.

We will use a regular expression that extracts all numbers from a string and replaces all the occurrences with a number.

\d – This is a regular expression that matches any digit from 0 to 9.

package org.arpit.java2blog.entry;

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String replaceAll = "Peter is 29 years old, and Jane is 60 years old";
        String replaceAllNumbers = replaceAll.replaceAll("\\d\\d", "30");
        System.out.println(replaceAllNumbers);
    }
}

Output:

Peter is 30 years old and Jane is 30 years old

If you want to remove substring from String, you can use empty String with replaceAll() method

Here is an example:

package org.arpit.java2blog;
public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String replaceAll = "Peter is 29 years old, and Jane is 60 years old";
        String replaceAllNumbers = replaceAll.replaceAll("\\d\\d", "");
        System.out.println(replaceAllNumbers);
    }
}

Output:

Peter is years old, and Jane is years old

Using StringBuilder’s delete() method to remove substring from String in Java

The StringBuilder contains a mutable sequence of characters used to modify a string by adding and removing characters.

The empty constructor of StringBuilder creates a string builder with an initial capacity of 16 characters, and if the internal buffer overflows, it is automatically made larger.

The delete() method accepts two int parameters indicating the start and the end of the substring to be removed from the string.

The start index is inclusive, while the last index is exclusive as it deducts 1 from the second parameter.

When the start is equal to the end, no changes are made, and a StringIndexOutOfBoundsException is thrown when the start is negative, greater than the length of the string, or greater than the end of the string.

public static void main(String[] args){
         StringBuilder stringBuilder = 
                new StringBuilder("Abdul quit drinking alcohol");

        //The last index = 19-1 = 18
        StringBuilder builder = stringBuilder.delete(11, 19);

        System.out.println(builder.toString());
}

Output:

Abdul quit alcohol

Using StringBuilder’s replace() method to remove substring from String in Java

The replace() method is similar to the delete() method, only that it has a third parameter that replaces the characters that have been removed from the string.

If the string you want to replace is large, the size will be increased to accommodate its length.

This method also returns a StringBuilder, and you can use the toString() method to print out the modified string.

public static void main(String[] args){
         StringBuilder stringBuilder = 
                new StringBuilder("The car broke down on a hill");

        //The last index = 7-1 = 6
        StringBuilder builder = stringBuilder.replace(4, 7, "bike");

        System.out.println(builder.toString());
}

Output:

The bike broke down on a hill

Conclusion

In this tutorial, you have learned how to remove a substring from a string by replacing and deleting characters. The methods covered include using string replace(),replaceFirst(), replaceAll() and finally using StringBuilder delete() and replace() methods.

]]>
https://java2blog.com/remove-substring-from-string-in-java/feed/ 0