限制字符串中的字符数,并切断其余字符 [英] Limiting the number of characters in a string, and chopping off the rest

查看:177
本文介绍了限制字符串中的字符数,并切断其余字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在日志的末尾创建一个汇总表,其中一些值在一个类中获得
。该表需要以固定宽度
格式打印。我已经有了这样做的代码,但我需要将字符串,
双精度和整数限制为在代码中硬编码的固定宽度大小。

I need to create a summary table at the end of a log with some values that are obtained inside a class. The table needs to be printed in fixed-width format. I have the code to do this already, but I need to limit Strings, doubles and ints to a fixed-width size that is hard-coded in the code.

所以,假设我要打印一个固定宽度的表,其中

So, suppose I want to print a fixed-width table with

    int,string,double,string
    int,string,double,string
    int,string,double,string
    int,string,double,string

    and the fixed widths are: 4, 5, 6, 6.

如果某个值超过此宽度,则需要切断最后一个字符。所以
例如:

If a value exceeds this width, the last characters need to be cut off. So for example:

    124891, difference, 22.348, montreal

需要打印的字符串应该是:

the strings that need to be printed ought to be:

    1248 diffe 22.348 montre

我想我需要在构造函数中强制执行某些操作
字符串不超过一定数量的字符。我可能会
将双打和整数投入一个字符串,所以我可以强制执行最大宽度
的要求。

I am thinking I need to do something in the constructor that forces a string not to exceed a certain number of characters. I will probably cast the doubles and ints to a string, so I can enforce the maximum width requirements.

我不知道哪个方法执行此操作或者如果字符串可以实例化为
表现得很好。使用格式化程序只能帮助
fixed-with格式化打印字符串,但实际上并不是
砍掉超过​​最大长度的字符。

I don't know which method does this or if a string can be instantiated to behave taht way. Using the formatter only helps with the fixed-with formatting for printing the string, but it does not actually chop characters that exceed the maximum length.

推荐答案

用它来切断不需要的字符:

Use this to cut off the non needed characters:

String.substring(0, maxLength); 

示例:

String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234" 

确保在未获得IndexOutOfBoundsException时输入字符串小于预期长度请执行以下操作:

To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:

int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);

如果你希望你的整数和双精度具有一定的长度,那么我建议你使用NumberFormat 可以格式化您的数字,而不是切断其字符串表示形式。

If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.

这篇关于限制字符串中的字符数,并切断其余字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆