java 学习笔记(二) 字符串分割

  写个小程序用到将输入的路径字符串分割成路径和文件名两个字符串,就学习了下java中的字符串分割。网上查了下有两种方法。第一种是用String的split方法,另一种是StringTokenizer。应该还是有其他方法的,希望了解的同学们可以指点一下。

  一.split,直接上代码吧。

 
  
1 public class SplitTest {
2
3
4 public static void main(String[] args) {
5 String path = " d:\\a\\b\\c.txt " ;
6 String fileName;
7 String parentPath;
8
9 String[] filePath = path.split( " \\\\ " ); // 部分标点符号不能直接使用,需要加\\ 而恰好要分割的符号也是\\
10
11 // 分割后filePath[0] = d:
12 // filePath[1] = a
13 // filePath[2] = b
14 // filePath[3] = c.txt
15  
16 fileName = filePath[filePath.length - 1 ];//这里取到最后一个数组单元,即文件名
17
18 char [] pathTemp = new char [ 50 ];
19 path.getChars( 0 , path.length(), pathTemp, 0 );
20 // 将文件名之前的字符串都拷贝到路径字符串中
21   parentPath = String.valueOf(pathTemp, 0 , path.length() - fileName.length() - 1 );
22
23 System.out.println(parentPath);
24 System.out.println(fileName);
25
26 }
27
28 }

输出结果为

  d:\a\b

  c.txt

由于刚刚接触java,代码中很多字符串操作感觉写的不是很好,望高手们多加指点,小弟感激不尽。

  二.StringTokenizer

 
  
1 import java.util.StringTokenizer;
2
3   public class tokenizerTest {
4
5
6 public static void main(String[] args) {
7 String path = " d:\\a\\b\\c.txt " ;
8 String fileName;
9 String parentPath;
10
11 StringTokenizer testTok = new StringTokenizer(path, " \\\\ " );
12 String[] filePath = new String[testTok.countTokens()];
13
14 int i = 0 ;
15 while (testTok.hasMoreTokens()){
16 filePath[i ++ ] = testTok.nextToken();
17 }
18
19 fileName = filePath[i - 1 ];
20
21 char [] pathTemp = new char [ 50 ];
22 path.getChars( 0 , path.length(), pathTemp, 0 );
23 // 将文件名之前的字符串都拷贝到路径字符串中
24   parentPath = String.valueOf(pathTemp, 0 , path.length() - fileName.length() - 1 );
25
26 System.out.println(parentPath);
27 System.out.println(fileName);
28
29
30 }
31
32 }
其实两者实现起来很类似,也许现在用的比较少还没有发现两者各适合什么情况,慢慢研究吧。。。

转载于:https://www.cnblogs.com/lazygunner/archive/2011/07/05/2098389.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值