Java String操作及类型转换

来源:互联网 发布:数据科学实战 微盘 编辑:程序博客网 时间:2024/06/04 20:12

常用字符串操作

方法 效果 s.length() 返回s字符串长度 s.charAt(2) 返回s字符串中下标为2的字符 s.substring(0, 4) 返回s字符串中下标0到4的子字符串 s.indexOf(“Hello”) 返回子字符串”Hello”的下标 s.startsWith(” “) 判断s是否以空格开始 s.endsWith(“oo”) 判断s是否以”oo”结束 s.equals(“Good World!”) 判断s是否等于”Good World!” ==只能判断字符串是否保存在同一位置。需要使用equals()判断字符串的内容是否相同。 s.compareTo(“Hello Nerd!”) 比较s字符串与”Hello Nerd!”在词典中的顺序,返回一个整数,如果<0,说明s在”Hello Nerd!”之前;如果>0,说明s在”Hello Nerd!”之后;如果==0,说明s与”Hello Nerd!”相等。 s.trim() 去掉s前后的空格字符串,并返回新的字符串 s.toUpperCase() 将s转换为大写字母,并返回新的字符串 s.toLowerCase() 将s转换为小写,并返回新的字符串 s.replace(“World”, “Universe”) 将”World”替换为”Universe”,并返回新的字符串

String to Int/Float/Double

public class TypeChange {   //change the string type to the int type   public static int stringToInt(String intstr)   {     Integer integer;     integer = Integer.valueOf(intstr);     return integer.intValue();   }   //change int type to the string type   public static String intToString(int value)   {     Integer integer = new Integer(value);     return integer.toString();   }   //change the string type to the float type   public static float stringToFloat(String floatstr)   {     Float floatee;     floatee = Float.valueOf(floatstr);     return floatee.floatValue();   }   //change the float type to the string type   public static String floatToString(float value)   {     Float floatee = new Float(value);     return floatee.toString();   }   //change the double type to the string type   public static double stringToDouble(String doublestr)   {     Double doubleee;     doubleee = Double.valueOf(doublestr);     return doubleee.doubleValue();   }   //change the double type to the string type   public static String doubleToString(double value)   {     Double doubleee = new Double(value);     return doubleee.toString();   }}
原创粉丝点击