Java 字符串限制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15727434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:39:11  来源:igfitidea点击:

Java String Limit

javastringnetbeanslimit

提问by user2228777

I am new to java (previously only worked with sql) and I am attempting to set a length limit for my string variable. Basically I have a username field that can only be 6 characters long.

我是 Java 新手(以前只使用 sql),我正在尝试为我的字符串变量设置长度限制。基本上我有一个只能是 6 个字符长的用户名字段。

I am trying the following:

我正在尝试以下操作:

private String username (6);

I am assuming this is not the correct format. Does anyone know how i can do this in java correctly?

我假设这不是正确的格式。有谁知道我如何在java中正确地做到这一点?

回答by eis

Some other answers have claimed that "There is no way to limit Strings in java to a certain finite number through inbuilt features", and suggested rolling ones own. However, Java EE validations API is meant for just this. An example:

其他一些答案声称“无法通过内置功能将 java 中的字符串限制为某个有限的数字”,并建议滚动自己的。但是,Java EE 验证 API 仅用于此目的。一个例子:

import javax.validation.constraints.Size;

public class Person {
      @Size(max = 6)
      private String username;
}

Further info on how to use Validation API, see this threadfor example. Hibernate validatoris the reference implementation (usage).

有关如何使用验证 API 的更多信息,请参阅此线程示例。Hibernate 验证器是参考实现(用法)。

In short, when annotating an object as @Valid, validations done in annotations will be enforced.

简而言之,当将对象注释为 @Valid 时,将强制执行在注释中完成的验证。

回答by stevenelberger

What you suggested is not the correct way to do what you want. Try using:

你建议的不是做你想做的正确方法。尝试使用:

private int stringLimit = 6;
// Take input from user
private String username = inputString.substring(0,stringLimit);

For example:

例如:

inputString = "joelspolsky";
private String username = inputString.substring(0,stringLimit);
// username is "joelsp"

回答by Achintya Jha

You can try soemthing like this:Take input from user then validate that string by using following function.

您可以尝试这样的操作:从用户获取输入,然后使用以下函数验证该字符串。

String output ="";
public boolean set(String str, int limit){
      if(str.length() <= limit){
            output= str;
            return true;
      }
      else
        return false;
 }

回答by Deepak Bala

There is no way to limit Strings in java to a certain finite number through inbuilt features. Strings are immutable and take the value that you provide in their constructor. You will need to write code manually to do this.

无法通过内置功能将 java 中的字符串限制为某个有限的数字。字符串是不可变的,并采用您在其构造函数中提供的值。您将需要手动编写代码来执行此操作。

Use the length()function to determine the length of the String and do not allow lengths greater than 6.

使用该length()函数确定字符串的长度,并且不允许长度大于 6。

if( username.length() > 6 )
{
    throw new RuntimeException("User name too long");
}

One of the options you have is to throw an exception and then handle it elsewhere. Or you can display an alert to the user immediately after you encounter the problem.

您拥有的选择之一是抛出异常,然后在其他地方处理它。或者您可以在遇到问题后立即向用户显示警报。

回答by Bhargav

SubString() won't be suitable for this. If the length of input string is less than limit StringIndexOutOfBoundsExceptionwill be thrown. I think you can use StringBuilderfor this.

SubString() 将不适合于此。如果输入字符串的长度小于限制StringIndexOutOfBoundsException将被抛出。我认为您可以为此使用StringBuilder

StringBuilder buider = new StringBuilder(username);
builder.setLength(6);
String restName = builder.toString().trim();

回答by Andremoniy

In this case annotationmechanism can be useful, if of course, you know what is this.

在这种情况下,annotation机制可能很有用,当然,如果您知道这是什么。

You can create your own annotation, something like:

您可以创建自己的注释,例如:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MaxLength {
    int value();
}

And use it like:

并像这样使用它:

@MaxLength(6)
private String username;

Then you have to post-process such objects in special post-processor, which you have to create manually.

然后您必须在特殊的后处理器中对此类对象进行后处理,您必须手动创建这些对象。

回答by ivan

example to cut the length of URL

减少URL长度的例子

if (getURLitem.length() >= 15) {
                int stringLimit = 15;
                final String smallURL = getURLitem.substring(0, stringLimit);
                //show short string in textview...

                TextView urlLink = (TextView) findViewById(R.id.url_link);
                urlLink.setText(smallURL);

                // Set On click listener and open URL below
                ...........
            } else {
                //show full string in textview...
                TextView urlLink = (TextView) findViewById(R.id.url_link);
                urlLink.setText(getURLitem);

                // Set On click listener and open URL below
                ...........
            }