首页 >php教程 >PHP开发 >String字符串截取的四种方式总结

String字符串截取的四种方式总结

高洛峰
高洛峰原创
2016-12-03 17:00:071855浏览

如下所示:

import java.util.StringTokenizer;
import java.util.regex.Pattern;
 
import org.junit.Test;
 
public class TestStringToken {
 
  @Test
  public void subSting() {
    String str = "java,javac,javae";
    String s1 = str.substring(2);//"va,javac,javae"
    String s2 = str.substring(0,2);//"ja"
    System.out.println(s1);
    System.out.println(s2);
  }
 
  @Test
  public void stringTokenizer() {
    String str = "java,javac,javae";
    StringTokenizer stringTokenizer = new StringTokenizer(str, ",");
 
//   while (stringTokenizer.hasMoreElements()) {
//     Object object = (Object) stringTokenizer.nextElement();
//     System.out.println(String.valueOf(object));
//     
//   }
    while (stringTokenizer.hasMoreTokens()) {
      System.out.println(stringTokenizer.nextToken());
    }
  }
  @Test
  public void split() {
    String str = "java,javac,javae";
    String[] s = str.split(",");
    for (String string : s) {
      System.out.println(string);
    }
  }
  //使用正则表达式
  @Test
  public void pattern() {
    String str = "java,javac,javae";
    Pattern p = Pattern.compile(",");
    String[] s = p.split(str);
    for (String string : s) {
      System.out.println(string);
    }
  }
 
}


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn