我有一個非常長的字符串,如「移動事件」,他們可以是任何長度的字符串,我想要顯示....說一定的長度後,如何做到這一點?如何包裝一個字符串
0
A
回答
3
你可以做這樣的事情 -
String str = "The event for mobile is here";
String temp = "";
if(str !=null && str.length() > 10) {
temp = str.substring(0, 10) + "...."; // here 0 is start index and 10 is last index
} else {
temp = str;
}
System.out.println(temp);
輸出會 - 事件....
4
使用Apache Common library的WordUtils類。
static String wrap(java.lang.String str,
int wrapLength, java.lang.String newLineStr, boolean wrapLongWords)
例子 -
String str = "This is a sentence that we're using to test the wrap method";
System.out.println("Original String 1:\n" + str);
System.out.println("\nWrap length of 10:\n" + WordUtils.wrap(str, 10));
System.out.println("\nWrap length of 20:\n" + WordUtils.wrap(str, 20));
System.out.println("\nWrap length of 30:\n" + WordUtils.wrap(str, 30));
1
String template = "Hello I Am A Very Long String";
System.out.println(template.length() > 10 ? template.substring(0, 10) + "..." : template);
你可以只看長度,然後做一個substring
。
或者如果你可以使用Apache的普通Util,那麼使用這個WordUtils.wrap()。
我沒有做一個好的搜索較早,this SO Post正是你想要的
1
如果你想完整的單詞,然後做到這一點:
public static void shortenStringFullWords(String str, int maxLength) {
StringBuilder output = new StringBuilder();
String[] tokens = str.split(" ");
for (String token: tokens) {
if (output.length() + token.length <= maxLength - 3) {
output.append(token);
output.append(" ");
} else {
return output.toString().trim() + "...";
}
}
return output.toString().trim();
}
1
你可以這樣做像這樣
String longString = "lorem ipusum ver long string";
String shortString = "";
int maxLength = 5;
if(longString != null && longString.length() > maxLength) {
shortString = longString.substring(0,maxLength - 1)+"...";
}
在這裏,您可以將maxLength更改爲所需的數字。
1
String myString ="my lengthy string";
int startIndex=0, endIndex=myString.length(), lengthLimit = 10;
while(startIndex<endIndex) {
System.out.println(myString.substring(startIndex, startIndex+lengthLimit));
startIndex = startIndex+lengthLimit+1;
}
相關問題
- 1. 如何確定一個字符串包含字符串
- 2. 如何檢查一個字符串是否包含一個子字符串 - mysql
- 3. 如何找到一個字符串是否包含在另一個字符串
- 4. 如何提取第一個子字符串我包含一個字符串/?
- 5. 如何檢查一個字符串是否包含任何一些字符串
- 6. 包裝字符串PHP
- 7. 如何檢查一個字符串是否至少包含另一個字符串中的一個字符?
- 8. 如何確定一個字符串至少包含一個字母字符?
- 9. 如何使用標籤包裝字符的字符串?
- 10. Javascript - 如何檢查一個字符串是否包含多個子字符串
- 11. 將多個變量包裝成一個字符串
- 12. 如何檢查一個字符串是否包含來自另一個字符串的任何字符?
- 13. 如何用R中的一個X包圍一個字符串?
- 14. 如何將字符串值除以另一個字符串值,每個字符串值均包含數字值
- 15. 如何判斷一個字符串是否包含Guid作爲子字符串?
- 16. 如何檢查一個字符串是否包含特定的子字符串
- 17. Smalltalk:如何檢查一個字符串只包含數字?
- 18. Java,如何檢查一個字符串是否包含數字?
- 19. 包裝線在python:打破一個參數字符串
- 20. 包裝bash命令是一個字符串
- 21. 更改地區和其他包裝得到一個字符串
- 22. 變量需要包裝成一個字符串
- 23. 如何檢查至少包含一個字母和一個數字的字符串字符串
- 24. 如何確定一個字符串是否包含非字母數字字符?
- 25. 確定一個字符串是否包含任何一組字符串
- 26. 如何檢查一個TextView是否包含某個字符串
- 27. 如何在一個字符串中搜索兩個字符串?
- 28. PHP字符串包含一個子字符串
- 29. 字符串除了與另一個字符串包含「+」
- 30. Applescript:檢查一個字符串是否包含空字符串?