BM Balmiki Mandal 06 May 2023 1 views 0 comments Core Java

Split a String Every n Characters in Java

Split a String Every n Characters in Java

If you have a string that is too long and need to split it into smaller strings, Java provides a perfect way to accomplish this task. The function that can be used for the same is substring(). This function will help you break down a given string into multiple strings of length n characters.

To use this function first declare and initialize a string variable. In this example we will use the string “splitEveryNCharacter”.

String str = "splitEveryNCharacter";

Now in order to split this string into substring of length 5 (you can replace the value with any number) you will be using the following syntax.

for (int i = 0; i < str.length(); i+=5) 
{ 
	System.out.print(str.substring(i, Math.min(str.length(), i + 5))); 
} 

In the above syntax, You are essentially using a loop to iterate through each character every 5. The substring() function takes in two parameters: start index and end index. Hence as you iterate through each loop the start=i and end=Math.min(str.length(), i + 5). This will make sure that we don’t exceed the length of the string. At the end of the last iteration, the variable ‘i’ i.e. the start will be at the length of the string and the min function will avoid exceeding the length of the string.

The output of the above code will look like below.

spli
tEve
ryNC
harac
ter

0 Comments

No comments yet, Be the first to comment.

Post a Comment

Please sign in to post a comment.

Related Posts

Unlock the Ins and Outs of JavaScript Engines and Runtimes

What is a JavaScript Engine? A JavaScript engine is a program or interpreter which executes JavaScript code....

BM Balmiki Mandal 05 Sep 2023
Implementing HMACSHA256 Algorithm in Java with Key

Introducing HMACSHA256 in Java with Key HMACSHA256 is an authentication algorithm designed to secure data, su...

BM Balmiki Mandal 30 Aug 2023
HMACSHA256 Java Example - Creating Secure Message Authentication

HMACSHA256 Java Example HMACSHA256 is an advanced encryption algorithm that allows developers to create encry...

BM Balmiki Mandal 30 Aug 2023