Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




center( ) FUNCTION


center( ) Function


The center() Function is used to centrally align a String.


Example :


x = "hello"
y = x.center(10)
print(y)   


Output :



  hello

In the above code, we have declared a String 'hello'.


x = "hello"

java_Collections

Then we have used the 'x.center(10)' function to reserve '10' blocks and place 'hello' in between.


And what about the empty places in left and right? Well! They would be filled by white spaces ( i.e. ' ')


y = x.center(10)

And assign to variable 'y'.


java_Collections

So, 10 blocks are reserved for the String and the left side of the String 'hello' is filled with 2 white spaces and the right side is filled with 3 white spaces.


And, we print the value of 'y'.


print(y)

And we got the below output.


 hello

Now, let us say we want to place '10' Asterix '*', and insert the String 'hello' in between them.


Example :


x = "hello"
y = x.center(10,'*')
print(y)  


Output :



  **hello***

In the above code, we have declared a String 'hello'.


x = "hello"

java_Collections

Then we have used the 'x.center(10,'*')' function to reserve '10' blocks and place 'hello' in between.


And what about the empty places in left and right? Well! They would be filled by Asterix '*' this time.


y = x.center(10,'*')

And assign to variable 'y'.


java_Collections

So, 10 blocks are reserved for the String and the left side of the String 'hello' is filled with 2 Asterix '*' and the right side is filled with 3 Asterix '*'.


And, we print the value of 'y'.


print(y)

And we got the below output.


**hello***