简体   繁体   English

如何在 Java 中创建 padString 函数?

[英]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的方法,它接受两个参数:一个字符串和一个表示长度的整数。例如,

padString ("hello", 8)

should return "hello " (that's three spaces in there at the end).应该返回"hello " (最后是三个空格)。 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" .应该返回"congratualtions"

I have no idea on how to approach this being pretty new to Java.我不知道如何处理这个对 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?需要 <= 0 填充字符? 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.您可以使用.length()方法找到字符串的长度。

Even thought this post is about 2 years old.甚至认为这篇文章大约有 2 年的历史。 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.一个可能更符合他们在初级 Java 课程中所处的位置,假设他们与我同时学习。

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).您可以在System.out使用printf方法(需要 Java 1.6 或更高版本,它是一种新的PrintStream方法)。 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:填充在 printf 参数中指定为 30,并左对齐:

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." “编写一个名为 padString 的方法,它接受两个参数:一个字符串和一个表示长度的整数。”

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

"For example,padString("hello", 8) should return "hello"." "例如,padString("hello", 8) 应该返回"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"." “如果字符串的长度已经至少与长度参数一样长,则您的方法应返回原始字符串。例如,padString("congratulations", 10) 应返回“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.您可能需要查看 Java 的 String 类文档。 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.摘自@John C 的评论,并添加了“%-”。

Sorry @John CI cannot edit your comment or add one below yours.抱歉,@John CI 无法编辑您的评论或在您的评论下方添加评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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