简体   繁体   中英

How do I create a padString function in Java?

Every other question I have seen in my book I had at least some understanding of what the book was asking but this one I have no idea on how to approach it. It goes:

"Write a method called padString that accepts two parameters: a String and an integer representing a length. For example,

padString ("hello", 8)

should return "hello " (that's three spaces in there at the end). 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)

should return "congratualtions" .

I have no idea on how to approach this being pretty new to Java. This is supposed to be a beginner's homework so I suppose the method is very simple. Please show me how to do this and explain the steps if you can. Please and Thank you to whoever helps.

So your function should do something like this:

  1. Determine number of padding characters required.

  2. Need <= 0 padding characters? return input string

  3. Otherwise, create a string with required padding characters, then return input string + required padding characters

You can find a string's length with the .length() method.

Even thought this post is about 2 years old. I just recently had this question for a homework. And I thought it might help other beginners that might come across this problem to see a simpler way of solving this problem.

One that will probably be more in line to where they are in their beginner java course assuming they are getting this around the same time that I did.

Of course you should remove the dashes in the loop and use spaces to get credit for the assignment, that is there just to show you that it works.

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

             padString("hello",10);
          }

          public static String padString( String s, int len) {

             int s_length = s.length();
             int diff = len - s_length;
             String newString;

             newString = "";

             for (int x = 0 ; x < diff; x++) {
                newString += "-";
             }

             newString = newString + s;


             return new String;
             }
       }

You could use the printf method in System.out (needs Java 1.6 or later, it's a new PrintStream method). Hake a look at an interesting example below, where the output is (specified below code). The padding is specified in the printf argument as 30, and is justified left:

package pft;

public class PrintfTest {
 public static void main(String[] args) {
        int padding = 30;
     String s = "hi!";
     System.out.printf("'%0$-" + padding + "s'", s);
 }
}

prints: 'hi!                           '.

Taking it piece at a time (and without giving you all the code):

"Write a method called padString that accepts two parameters: a String and an integer representing a length."

public static ??? padString(String str, int len)

"For example,padString("hello", 8) should return "hello"."

public static String padString(String str, int len)
{
    throw new Error("not implemented yet");
}

"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) should return "congratualtions"."

EDIT: you fixed the question...

public static String padString(String str, int len)
{
    // if the str.length is greater than len
    //     return str

    // this next part is very simple, not a very good way but gets you 
    // started. Once you have it working look at StringBuilder and .append.

    // int val = the difference in length between the two strings

    // for i = 0; i is less than val; i++
    //     str += " ";           

    // return str
}
public class PadString {
    public static void main(String[] args) {
        String str = "hello";
        str = padStr(str, 10, ' ');
    }

    static String padStr(String s, int len, char c) {

        int n = len - s.length();
        if (n <= 0)
            return s;
        StringBuilder b = new StringBuilder(s);
        for (int i = 0; i < n; i++)
            b.append(c);
        return b.toString();

    }
}

You may want to take a look at Java's String class documentation. Look for a method that returns the length of the string...

public static String padString(String str, int len) 
{ 

int lengt=str.length();
if(lengt==len||lengt>len)
 return str;
else if(lengt<len){
 String spacstr="";
 for(var i=lengt;i<len;i++){
    spacstr+="$";
 }
 return str+spacstr;
}

} 

///more generalized  by accepting pad character



public static String padString(String str, int len,String padChar) 
{ 

int lengt=str.length();
if(lengt==len||lengt>len)
 return str;
else if(lengt<len){
 String spacstr="";
 for(var i=lengt;i<len;i++){
    spacstr+=padChar;
 }
 return str+spacstr;
}

} 
public String padString (String s, int padding) {

   return String.format("%-" + padding + "s", s);

} 

This is the better solution for me. Taken from the comment of @John C, with the "%-" added.

Sorry @John CI cannot edit your comment or add one below yours.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM