Seho Lee
Seho Lee

Reputation: 4108

How can I limit string length in android?

suppose I have a string below.

"This is my string blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah
blah blah blah blah blah blah blah blah blah"

I only want to show "This is my string" part and cut "blah" part.

So... I want to make my String as "This is my string" and do not want to

show my string as "this is my string blah blah blah blah".

Is there anyway to cut or limit String value in android?

Upvotes: 4

Views: 23921

Answers (3)

Ray Li
Ray Li

Reputation: 7919

The answer marked as correct is poor and should not be used. If the supplied string is less than the substring range, then the code will crash. Check that the string exceeds the length you want to shorten to first.

public static String truncate(String str, int len) {
if (str.length() > len) {
  return str.substring(0, len) + "...";
} else {
  return str;
}}

Upvotes: 7

kosa
kosa

Reputation: 66637

Substring the string to 50 characters, which returns first 50 characters

You may need to something like this:

 String s = blahString.substring(0,50);

Then set those to your textbox:

yourText.setText(s);

Upvotes: 21

Kumar Bibek
Kumar Bibek

Reputation: 9117

You could use ellipsize for TextViews for truncating the text if they are longer than the view. In that case, you don't need to hard code the 50 character limit.

http://developer.android.com/reference/android/widget/TextView.html#attr_android:ellipsize

Upvotes: 10

Related Questions