现在的位置: 首页 > 综合 > 正文

java中substring的用法和charAt()的用法

2018年01月08日 ⁄ 综合 ⁄ 共 1651字 ⁄ 字号 评论关闭

java中substring的用法

str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str;

str=str.substring(int beginIndex,int endIndex);截取str中从beginIndex开始至endIndex结束时的字符串,并将其赋值给str;

以下是一段演示程序:

public class StringDemo{

public static void main(String agrs[]){

   String str="this is my original string";

   String toDelete=" original";

  

   if(str.startsWith(toDelete))

    str=str.substring(toDelete.length());

   else

    if(str.endsWith(toDelete))

     str=str.substring(0, str.length()-toDelete.length());

else

    {

     int index=str.indexOf(toDelete);

     if(index!=-1)

     {

      String str1=str.substring(0, index);

      String str2=str.substring(index+toDelete.length());

      str=str1+str2;

     }

     else

      System.out.println("string /""+toDelete+"/" not found");

    }

   System.out.println(str);

}

}

(原文引用自:http://hi.baidu.com/ccsos/blog/item/42ff84afe6e62bcd7dd92a62.html)

补充:str=str.substring(int beginIndex,int endIndex);中最终得到的值:

         beginIndex =< str的值 < endIndex

以上补充内容是我自己以前的一点理解

近日在API中看到对它的注解,

把它发布在下面以便更多的和我一样的初学者更好的理解上面的程序

substring

public String substring(int beginIndex,
                        int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,一直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex

示例:

 "hamburger".substring(4, 8) returns "urge"
 "smiles".substring(1, 5) returns "mile"
 
参数:
beginIndex - 开始处的索引(包括)。
endIndex - 结束处的索引(不包括)。
返回:
指定的子字符串。
抛出:
IndexOutOfBoundsException - 如果 beginIndex 为负,或 endIndex 大于此 String 对象的长度,或 beginIndex大于 endIndex

charAt()的用法:

charAt()的方法返回值是char类型的
你的a1,a2都是String类型的
两种数据类型肯定不兼容的

class b{ 
public static void main(String args []){ 
String s=new String("abcdefg"); 
char a1,a2;//改下这里看可以不 
a1=s.charAt(0); 
a2=s.charAt(6); 
//这里改成这样最好
//a2=s.charAt(s.length-1);
System.out.println(a1); 
System.out.println(a2);}}

抱歉!评论已关闭.