作者kentyeh (kent)
看板java
标题Re: [问题] String内找出第一个可见字元
时间Thu Jun 10 16:03:12 2010
※ 引述《scott260202 (Cake)》之铭言:
: 我有读入一整行的String 一整行喔
: 所以会有很多空白字元
: 例如
: " a 123 b \n"
: 以上字串已经存在一个String里面了
: 有什麽指令或方法可以抓出 那个'a'
: // 因为必须忽略後面的东西 且下次读东西的时候不能读到他们
: 所以不能用跳过空白的方式读一个小字串
: 请各位高手帮个忙吧 感恩^.=
看到回文使用 replaceAll 将空白字元置换,
但是WhiteSpace其实包含了[ \t\n\x0B\f\r], 我会建议使用 regular explression
给您个sample , 具体用法请参考API Doc
Pattern p = Pattern.compile("\\w");
String msg = " \t \n \u000B \f \r a 123 b \n";
Matcher m = p.matcher(msg);
if(m.find())
System.out.println(String.format("find %s at %d position",
msg.charAt(m.start()),m.start()));
输出结果为
find a at 15 position
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.20.140.43
1F:→ ogamenewbie:msg.trim().charAt(0) 的结果不对嘛? @_@a 06/10 16:49
2F:→ kentyeh:msg.trim().charAt(0)可以,除非msg不全由whitespace组成 06/10 20:50