Limiting the Number of Characters in a String, and Chopping Off the Rest

Limiting the number of characters in a string, and chopping off the rest

Use this to cut off the non needed characters:

String.substring(0, maxLength); 

Example:

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

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);

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.

Limiting string length and adding ... if truncated

It’s not clear when the SLF4J API will catch up, but the Java 8 core API allows to defer any potentially expensive calculation to the point after the logging level has been checked, so it does not happen if the particular level is not loggable:

import java.util.logging.Logger;

public class LogAbbr {
final static int LIMIT = 15;
public static void main(String[] args) {
Logger log=Logger.getAnonymousLogger();
String[] examples={"short string", "rather long string"};
for(String responseContent: examples) {
log.info(() -> String.format("RESPONSE: %."+LIMIT+"s%s",
responseContent, responseContent.length()<=LIMIT? "": "..."));
}
}
}

Note that when LIMIT is a compile-time constant, "RESPONSE: %."+LIMIT+"s%s" is a compile-time constant too, hence, there is no need to manually inline the number, so using a named constant ensures consistency between the formatting string and the conditional.

Demo on Ideone:

Jan 27, 2017 11:53:20 AM Ideone main
INFO: RESPONSE: short string
Jan 27, 2017 11:53:20 AM Ideone main
INFO: RESPONSE: rather long str...

The following program demonstrates that the calculation does not happen, once the log level forbids it:

Logger log=Logger.getAnonymousLogger();
String[] examples={"short string", "rather long string"};
for(String responseContent: examples) {
log.info(() -> {
System.out.println("Potentially expensive operation with "+responseContent);
return responseContent;
});
log.setLevel(Level.SEVERE);
}

Demo on Ideone:

Limit String Length

You can use something similar to the below:

if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';

How to limit the number of characters in a String or attributed String in Swift

Start with the full string and the known two-line height of the label and its known width, and keep cutting words off the end of the string until, at that width, the string's height is less than the label's height. Then cut one more word off the end for good measure, append the ellipsis, and put the resulting string into the label.

In that way, I got this:

enter image description here

Notice that the word after "time" never starts; we stop at a precise word-end with the inserted ellipsis. Here's how I did that:

    lab.numberOfLines = 2
let s = "Little poltergeists make up the principle form of material " +
"manifestation. Now is the time for all good men to come to the " +
"aid of the country."
let atts = [NSFontAttributeName: UIFont(name: "Georgia", size: 18)!]
let arr = s.components(separatedBy: " ")
for max in (1..<arr.count).reversed() {
let s = arr[0..<max].joined(separator: " ")
let attrib = NSMutableAttributedString(string: s, attributes: atts)
let height = attrib.boundingRect(with: CGSize(width:lab.bounds.width,
height:10000),
options: [.usesLineFragmentOrigin],
context: nil).height
if height < lab.bounds.height {
let s = arr[0..<max-1].joined(separator: " ") + "…"
let attrib = NSMutableAttributedString(string: s, attributes: atts)
lab.attributedText = attrib
break
}
}

It is of course possible to be much more sophisticated about what constitutes a "word" and in the conditions for measurement, but the above demonstrates the general common technique for this sort of thing and should suffice to get you started.

How to limit the number of characters in a string displayed using Scala

How about this?

@info.notes.take(12)

Or java-style like this:

@info.notes.substring(0, 12)

How to trim a string to N chars in Javascript?

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

Can I limit TextView's number of characters?

Here is an example. I limit the sizewith the maxLength attribute, limit it to a single line with maxLines attribute, then use the ellipsize=end to add a "..." automatically to the end of any line that has been cut-off.

<TextView 
android:id="@+id/secondLineTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:maxLength="10"
android:ellipsize="end"/>


Related Topics



Leave a reply



Submit