在Java中重新格式化字符串

时间:2012-08-20 18:46:18

标签: android string text replace split

对于我的应用程序,我创建了一个QR代码,然后获取该位图并将文本添加到位图,但是我需要文本不要延长比位图更长的时间。所以我想要做的是通过取25个字符创建一个文本数组,然后找到该25个字符部分中的最后一个索引(“”)。在那个空间,我希望能够替换位于\ n的空间以开始一个新行。

所以计划是我有一个看起来像“Hello this is my name and I am longer than 25 charters and I have lots of spaces so that this example will work well.

的字符串

我希望它能够解决这个问题

Hello this is my name and
I am longer than 25 
charters and I have lots 
of spaces so that this 
example will work well.

为了做到这一点,我计算了25个字符,然后回到了最重要的空间,此时我点击了输入,我希望我的应用程序为我做这个。

我不是很擅长英语,所以如果有什么不合理的话告诉我,我会尝试解释它。感谢

2 个答案:

答案 0 :(得分:3)

我没有对此进行测试,但您可以尝试并根据需要进行调整

String fullText = "your text here";
String withBreaks = "";
while( fullText.length() > 25 ){
    String line  = fullText.substring(0,24);
    int breakPoint = line.lastIndexOf( " ");
    withBreaks += fullText.substring(0,breakPoint ) + "\n";
    fullText = fullText.substring( breakPoint );
withBreaks += fullText;

答案 1 :(得分:0)

char []方式(更喜欢C):

 public static String reduceLength(String s, int len){
    char [] c = s.toCharArray();
    int i=len, j=0, k;
    while(true){
     for(k=j; k<=i; k++){
         if (k >= s.length()) return new String(c);
         if (c[k] == ' ') j=k;
     }
     c[j] = '\n';
     i= j+ len;
    }
}

这不安全,只是我扔在一起的东西。

相关问题