基础问题出错:String的split(String str)方法用法

  如果一行只有一个回车换行符,那么这行用这个方法分开得到是一个0长度字符串,

下面这一句:

        if (charArray[0] != ' ') {

        sB.append(lineStr);

        sB.append("<br>");

      }

  就会出现indexOutOfBoundary这样的错误。

    //replace space at beginning and add "<br>" at end of every line

    String[] strArray = tempStr.split("\n");

    StringBuffer sB = new StringBuffer();

    for (int i = 0; i < strArray.length; i++) {

      String lineStr = strArray[i];

      //System.out.println(i +" : lineStr is: " + lineStr+"ok");

      char[] charArray = lineStr.toCharArray();

 

      //if no any char in this line,then add a <br> to the end of sB,

      //continue loop(don't excute the code behind continue in this loop).

      if (charArray.length == 0){

        sB.append("<br>");

        //System.out.println("come here.");

        continue;

      } 

     

      if (charArray[0] != ' ') {

        sB.append(lineStr);

        sB.append("<br>");

      }

完整代码:

package com.learndiary.website.util;

//import com.learndiary.util.*;

public class Util {

   

  public static String htmlFormat(String source) {

    //if (source==null) return null;//WHEN the source is "",run at line 33,will happen ArrayIndexOutOfBoundsException.

    //because char[0] don't exist a charactor.

    if ((source==null)||(source.length()==0)) return "";

    //replace "<>"

    String tempStr = source.replaceAll("<", "<").replaceAll(">", ">");

   

    //replace space at beginning and add "<br>" at end of every line

    String[] strArray = tempStr.split("\n");

    StringBuffer sB = new StringBuffer();

    for (int i = 0; i < strArray.length; i++) {

      String lineStr = strArray[i];

      //System.out.println(i +" : lineStr is: " + lineStr+"ok");

      char[] charArray = lineStr.toCharArray();

 

      //if no any char in this line,then add a <br> to the end of sB,

      //continue loop(don't excute the code behind continue in this loop).

      if (charArray.length == 0){

        sB.append("<br>");

        //System.out.println("come here.");

        continue;

      } 

     

      if (charArray[0] != ' ') {

        sB.append(lineStr);

        sB.append("<br>");

      } else {

      for (int j = 0; j < charArray.length; j++) {//if the first char of this String is space,need convert the first space to " "

        if (charArray[j] == ' ')//if there are several spaces at the begin of this String,need convert every space to " ".

          sB.append(" ");  

          else {//once meet a char isn't a space,then every space after this char needn't to be converted to " " in this string.

                //we can add the all charaters after this char,then ,add "<br>" to the end of this String.

            sB.append(charArray, j, charArray.length - j);

            //sB.append("<br>");

            break;

          }

        }

        sB.append("<br>");//need add " " to the end of this string.why put this sentence at here?

                          //if every character is space in this string,it also needs adding "<br>" at the end of this string.

      }

    }

   

    String resultTemp = sB.toString();

    String result = resultTemp.substring(0, resultTemp.length() - 4);       

    return result;

    //replaceAll(" ", " ").

  } 

 

  // Simple test:

  /* 

  public static void main(String[] args) throws Exception {

    String file = TextFile.read("gb5.txt");

    System.out.println("file is: \n" + file);

    String result = htmlFormat(file);

    System.out.println("result is \n" + result);

    write("test.txt", file);

    TextFile text = new TextFile("test.txt");

    text.write("test2.txt");

  }

   */

}

jdk1.4的文档:(还没有看懂,记在这里,慢慢看)

split

public String[] split(String regex,

                      int limit)

Splits this string around matches of the given regular expression.

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The string "boo:and:foo", for example, yields the following results with these parameters:

Regex Limit Result

: 2 { "boo", "and:foo" }

: 5 { "boo", "and", "foo" }

: -2 { "boo", "and", "foo" }

o 5 { "b", "", ":and:f", "", "" }

o -2 { "b", "", ":and:f", "", "" }

o 0 { "b", "", ":and:f" }

An invocation of this method of the form str.split(regex, n) yields the same result as the expression

Pattern.compile(regex).split(str, n)

Parameters:

regex - the delimiting regular expression

limit - the result threshold, as described above

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Throws:

PatternSyntaxException - if the regular expression's syntax is invalid

Since:

1.4

See Also:

Pattern

--------------------------------------------------------------------------------

split

public String[] split(String regex)

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result

: { "boo", "and", "foo" }

o { "b", "", ":and:f" }

Parameters:

regex - the delimiting regular expression

Returns:

the array of strings computed by splitting this string around matches of the given regular expression

Throws:

PatternSyntaxException - if the regular expression's syntax is invalid

Since:

1.4

See Also:

Pattern

One thought on “基础问题出错:String的split(String str)方法用法”

  1. 转自:http://www.javaresearch.org/article/60130.htm

    在java.lang包中有String.split()方法,返回是一个数组

    我在应用中用到一些,给大家总结一下,仅供大家参考:

    1、如果用“.”作为分隔的话,必须是如下写法:String.split("\\."),这样才能正确的分隔开,不能用String.split(".");

    2、如果用“|”作为分隔的话,必须是如下写法:String.split("\\|"),这样才能正确的分隔开,不能用String.split("|");

    “.”和“|”都是转义字符,必须得加"\\";

    3、如果在一个字符串中有多个分隔符,可以用“|”作为连字符,比如:“acount=? and uu =? or n=?”,把三个都分隔出来,可以用String.split("and|or");

Comments are closed.