231k views
1 vote
Write a method padString that accepts two parameters: a String and an integer representing a length. The method should pad the parameter string with spaces until its length is the given length. For example, padString("hello", 8) should return " hello". (This sort of method is useful when trying to print output that lines up horizontally.) If the string's length is already at least as long as the length parameter, your method should return the original string. For example, padString("congratulations", 10) would return "congratulations".

2 Answers

5 votes

Hi, you haven't provided the programing language in which you need the code, I'll explain how to do it using Python, and you can follow the same logic to make a program in the programing language that you need.

Answer:

#Python

def padString(string, integer):

if len(string)>=integer:

return(string)

else:

string = " "*(integer-len(string))+string

return(string)

Step-by-step explanation:

We define a method call padString that receives two parameters a string, and an integer representing the length. Inside the method is an 'if' statement that checks if the length of the string is longer than the integer if so a plain string is returned. If the 'if' is false the 'else' is activated and a string with the correct number of spaces is returned. To return the correct number of spaces you need to take the integer minus the length of the string and the result is the number of spaces required.

Write a method padString that accepts two parameters: a String and an integer representing-example-1
User Phil F
by
6.8k points
2 votes

Answer:

Following is the definition of method padString in Java:

public static String padString(String str, int length)

{

int i = 0;

String temp = str;

if(length>str.length())

{

while (i<(length - str.length()))

{

temp = " " + temp;

i++;

}

}

return temp;

}

Step-by-step explanation:

Sample program to demonstrate above method:

public class Main

{

public static void main(String[] args) {

System.out.println(padString("Hello", 8));

System.out.println(padString("congratulations", 10));

}

public static String padString(String str, int length)

{

int i = 0;

String temp = str;

if(length>str.length())

{

while (i<(length - str.length()))

{

temp = " " + temp;

i++;

}

}

return temp;

}

}

output:

Hello

congratulations

User Seebiscuit
by
7.0k points