Java分割线不起作用

时间:2013-11-26 09:47:42

标签: java

这是我的代码

//Numbers (Need errors on sort and numbers)
if(line.contains("n"))
{
    //split the line with space
    String[] LineSplit = line.split(" ");

    if(LineSplit[0].contains("n"))
    {
        //split the already split line  with "n thename "
        String[] LineSplit2 = line.split("n " + LineSplit[0] + " ");

        String text = "var " + LineSplit[1] + "=" + LineSplit2[0] +  ";";
        text = text.replace("\n", "").replace("\r", "");

        JAVASCRIPTTextToWrite += text;
    }

}

文字行是 n号1

输出应为

  

var number = 1;

但输出是

  

var number = n number = 1;

有人可以告诉我如何解决这个问题?代码看起来正确但不起作用:(

4 个答案:

答案 0 :(得分:0)

String number = "n number 1";
Sting[] temp = number.split(" ");
StringBuilder sb = new StringBuilder("var ");
sb.append(temp[1]);
sb.append(temp[2]);

如果您的条件满意,请执行此操作

答案 1 :(得分:0)

            String line = "n number 1";
            String JAVASCRIPTTextToWrite="";
            if(line.contains("n"))
            {
                //split the line with space
                String[] LineSplit = line.split(" ");

                if(LineSplit[0].contains("n"))
                {
                    //split the already split line  with "n thename "
                    String[] LineSplit2 = line.split("n " + LineSplit[1] + " ");
                    System.out.println( LineSplit[1]);
                    System.out.println( LineSplit2[0]);
                    String text = "var " + LineSplit[1] + "=" + LineSplit2[1] +  ";";
                    text = text.replace("\n", "").replace("\r", "");

                    JAVASCRIPTTextToWrite += text;
                    System.out.println(JAVASCRIPTTextToWrite);
                }

            }

答案 2 :(得分:0)

String line = "n number 1";

   if(line.contains("n"))
     {
    //split the line with space
    String[] LineSplit = line.split(" ");
        if(LineSplit[0].contains("n")) {
        //split the already split line  with "n thename "
        String LineSplit2 = line.substring(line.lastIndexOf(" ") + 1 , line.length());

        String text = "var " + LineSplit[1] + "=" + LineSplit2 +  ";";
        //text = text.replace("\n", "").replace("\r", "");
        System.out.println(text);
        }

   }

输出:

var number=1;

答案 3 :(得分:0)

我不知道你将字符串拆分两次的目的是什么。只是为了你想要的输出,我认为下面的解决方案就足够了。请查看下面的代码是否是您想要的:

    String line = "n number 1";
    String JAVASCRIPTTextToWrite = "";
    //Numbers (Need errors on sort and numbers)
    if(line.contains("n")) {
        //split the line with space
        String[] LineSplit = line.split(" ");

        if(LineSplit.length == 3) {
            StringBuilder text = new StringBuilder();
            text.append("var ");
            text.append(LineSplit[1]);
            text.append("=");
            text.append(LineSplit[2]);
            text.append(";");

            JAVASCRIPTTextToWrite += text.toString().replace("\n", "").replace("\r", "");
            System.out.println(JAVASCRIPTTextToWrite);
        }
    }