【问题标题】:Reformatting a String in Java在 Java 中重新格式化字符串
【发布时间】:2012-08-16 02:45:05
【问题描述】:

对于我的应用程序,我创建了一个 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 个字符,然后回到最讨厌的空间,此时我按 Enter,我希望我的应用为我执行此操作。

我的英语不是很好,所以如果有什么不明白的地方告诉我,我会尽力解释。谢谢

【问题讨论】:

  • 如果出现超过25个字符的字符串没有空格怎么办?

标签: android string text replace split


【解决方案1】:

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

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;

【讨论】:

  • 如果我没记错“withBreaks”我们我想打印出正确的内容吗?
  • 在末尾添加一行,以免遗漏最后几个字符。
【解决方案2】:

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

这不安全,只是我拼凑的东西。

【讨论】:

    猜你喜欢
    • 2011-02-20
    • 2017-10-27
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    相关资源
    最近更新 更多