java 温习之字符串(去除字符…

来源:互联网 发布:上班族副业知乎 编辑:程序博客网 时间:2024/06/15 22:33
建议:
个人更倾向于第二种(传智播客毕向东 老师的例子),第一种是我自己写的。
     第二种只有一次截取字符串操作,代码简介;
     而第一种多次截取字符串,代码略显臃肿。


package com.baidu.sep;
java <wbr>温习之字符串(去除字符串两端的空白【两种方法】)

public class StringTest5 
{
public static void main(String [] args)
{
String str = "-  g h - - ";

System.out.println(" 第一种方法输出的去除字符串两端空格的结果:"+ Trim(str));
System.out.println(" 第二种方法输出的去除字符串两端空格的结果:"+Trim2(str));
}
// 去除空格的方法1
private static String Trim(String str) 
{    String result=str;
int index_begin = 0;int index_end =result.length()-1;
for (;index_begin
{
if (index_begin
{
result = str.substring(++index_begin);
}else
break;
}
for (;index_end>0;index_end--)
{
if (index_begin
{
result = result.substring(0,index_end);
}else
break;
}
return result;
}
//去除空格的第二种方法
public static  String Trim2(String str)
{
int index_begin = 0;
int index_end = str.length()-1;
while(index_begin
index_begin++;
while(index_begin
index_end--;
return str.substring(index_begin,index_end+1);
}
}

0 0
原创粉丝点击