Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - String center() method



center() method returns a new string of length of numberOfChars and consists of the recipient padded on the left and right with space characters.

Syntax

The length of strings are determined using length() method.

String center(Number numberOfChars)
String center(Number numberOfChars, String paddingCharacter)

Parameters

numberOfChars − Number of characters for the new string.

paddingCharacter − a padding character to be used.

Return Value

This method returns a padded string.

Example - Padding a String

Following is an example of the usage of center() method of string in Groovy −

Example.groovy

class Example { 
   static void main(String[] args) { 
      String a = "Hello World"; 
      println(a.center(30)); 
   } 
}

Output

When we run the above program, we will get the following result −

          Hello World          

Example - Padding a String with hyphen character

Following is an example of the usage of center() method to pad a string with hyphens −

Example.groovy

class Example { 
   static void main(String[] args) { 	
      String a = "Hello World"; 
      println(a.center(30, "-")); 
   } 
}

Output

When we run the above program, we will get the following result −

----------HelloWorld----------

Example - Padding a String with * character

Following is an example of the usage of center() function on string literal in Groovy −

Example.groovy

class Example { 
   static void main(String[] args) { 	
      println("Hello World".center(30, "*")); 
   } 
}

Output

When we run the above program, we will get the following result −

**********Hello World**********
groovy_strings.htm
Advertisements