免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 742 | 回复: 0
打印 上一主题 下一主题

字符串操作 浮点运算【摘】 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-08-01 12:07 |只看该作者 |倒序浏览
字符串操作 浮点运算
在WEB开发中,数据类型中有一半是字符串的操作,Java本身对CHAR字符支持比较好,字符串就稍微复杂点.关于中文字符串处理可以参考我的另外一篇文章.这里主要讨论字符串的查找 替换等常用操作:
查找字符
/**
* 寻找特定字符匹配
*
* @param regex java regular-expression constructs
* @param s 原始字符串
* @return boolean
*/
public boolean FindSpec(String regex,String s)
{
  Pattern p = Pattern.compile(regex);
  Matcher m = p.matcher(s);
  if (m.find())
    return true;
  else
    return false;
  
}

在J2se1.4中,已经包含了类似PERL的强大字符串处理.例如,要检查字符串是否属于""形式:
String strs="";
boolean result=Pattern.matches("",strs);
if (result)
out.println("ok");
else
out.println("no");
结果是 ok, 如果strs="
具体文章见:
Java的正则表达式应用
字符串替换
/**
* 字符串替换,将 source 中的 oldString 全部换成 newString
*
* @param source 源字符串
* @param oldString 老的字符串
* @param newString 新的字符串
* @return 替换后的字符串
*/
public static String Replace(String source, String oldString, String newString) {
StringBuffer output = new StringBuffer();
int lengthOfSource = source.length(); // 源字符串长度
int lengthOfOld = oldString.length(); // 老字符串长度
int posStart = 0; // 开始搜索位置
int pos; // 搜索到老字符串的位置
while ((pos = source.indexOf(oldString, posStart)) >= 0) {
  output.append(source.substring(posStart, pos));
  output.append(newString);
  posStart = pos + lengthOfOld;
}
if (posStart
在j2se1.4当中,String提供了replaceAll().例如:
String strs="pppppqqqq abcdef sdfsdf";
String result1=strs.replaceAll("abc", "&&");
结果是pppppqqqq &&def sdfsdf
浮点运算
浮点运算一般欠缺是小数点后一位数,经常用到的是两个整数型相除要得到小数点后面好几位数.
使用字符型除整数型 得多个小数位的结果:
float num3=0.0f;
String click="0.023";
int view=8;
String radio=null;
if (view!=0){
  num3=Float.parseFloat(click)/view;
}
radio= new java.text.DecimalFormat("###.###").format(num3);
out.println("小数点后面保留三位:"+radio);
整数型除整数型 ,得多个小数位的结果:
int total=0.023;
int total2=8;
float num3=0.0f;
float total4 = (float)total2;
float total3 = (float)total;
if (total!=0){
  num3=total4/total3;
}
String radio= new java.text.DecimalFormat("###.###").format(num3);
out.println("小数点后面保留三位:"+radio);
DecimalFormat("###.###")可以任意定义位数,如DecimalFormat("###.##") 表示小数点后面保留两位!
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/21763/showart_148975.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP