Reputation: 15744
I found a class that does this, and it seems exactly what I need.
public static class StringUtil
{
public static String limit(String value, int length)
{
StringBuilder buf = new StringBuilder(value);
if (buf.length() > length)
{
buf.setLength(length);
buf.append("…");
}
return buf.toString();
}
}
I have a string called review
, and I use that class this way:
StringUtil.limit(review, 50);
It does not seem to be appending.
For what it's worth, it is for an Android app. This is being done in a PostExectute
method of AsyncTask
inside of a ListFragement
.
Am I doing this right?
Upvotes: 0
Views: 103
Reputation: 14640
Is the string you're sending in (review) longer than 50 characters? Note that the function only modifies the result if it's longer than the limit.
You also don't seem to be accepting the return value of the method. This method does NOT modify the argument value (since it can't), it returns a NEW String with the new value.
Try
String newreview = StringUtil.limit( review, 50 );
System.out.println( newreview );
Ok, you asked for a modification to go to the next space first. I didn't compile this, but it should be close.
public static String limit(String value, int length)
{
// note to Test this first, so you don't create a Buffer unnecessarily.
String ret = value;
if ( value.length() > length ) {
StringBuilder buf = new StringBuilder(value);
buf.setLength( length );
int cur = length;
while( cur < value.length() && value.charAt(cur) != ' ' ) {
buf.append( value.charAt(cur) );
}
if ( cur == value.length() ) {
ret = value; // we copied the whole string, as it turns out.
} else {
buf.append( "..." );
ret = buf.toString();
}
}
return value;
}
Upvotes: 1
Reputation: 2166
public static String limit(String value, int length)
{
return value+"...";
}
Upvotes: 0