【问题标题】:How to prepend "\n" to the last word of String?如何在字符串的最后一个单词前面加上“\n”?
【发布时间】:2016-10-25 07:52:34
【问题描述】:

我想在字符串的最后一个单词前面加上“\n” 例如

Hello friends 123

这里我想在单词“123”之前添加“\n”

我尝试了下面的代码,但不知道现在该做什么

String sentence  = "I am Mahesh 123"
String[] parts = sentence.split(" ");
String lastWord = "\n" + parts[parts.length - 1];

【问题讨论】:

标签: java android arrays string


【解决方案1】:
      Try this
            String sentence  = "Hello friends 123456";
            String[] parts = sentence.split(" ");
            parts[parts.length - 1] = "\n" + parts[parts.length - 1];

            StringBuilder builder = new StringBuilder();
            for (String part : parts) {
                builder.append(part);
                builder.append(" ");
            }

            System.out.println(builder.toString());

输出将是:~

 Hello friends

 123456

【讨论】:

  • 还在字符串末尾插入一个空格。它修剪字符串的末尾(它会用一个空格替换末尾的多个空格)。它会创建很多不必要的字符串。
【解决方案2】:

试试下面的代码...它会工作

parts[parts.length]=parts[parts.length-1];
parts[parts.length-1]="\n";

【讨论】:

    【解决方案3】:

    请试试这个。

    String sentence  = "I am Mahesh 123";
            String[] parts = sentence.split(" ");
            String string="";
            for (int i =0;i<parts.length;i++)
            {
                if (i==parts.length-1)
                {
                    string = string+"\n"+parts[i];
                }
                else
                string = string+" "+parts[i];
    
            }
            Toast.makeText(Help.this, string, Toast.LENGTH_SHORT).show();
    

    【讨论】:

      【解决方案4】:

      您想在字符串末尾添加一个换行符/换行符。 您可以通过lastIndexOf() 找到该空间,这将为您提供String sentence 中空间所在位置的int。 你可以在这里使用这个小例子:

      public class Main {
      
          public static void main(String[] args) {
              String sentence =  "I am Mahesh 123";
              int locationOfLastSpace = sentence.lastIndexOf(' ');
      
              String result = sentence.substring(0, locationOfLastSpace) //before the last word
                  + "\n" 
                  + sentence.substring(locationOfLastSpace).trim(); //the last word, trim just removes the spaces
      
              System.out.println(result);
          }
      }
      

      请注意,StringBuilder 未使用,因为Java 1.6 the compiler 将为您创建StringBuilder

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-11
        • 2019-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-21
        相关资源
        最近更新 更多