java中substring的⽤法和charAt()的⽤法java中substring的⽤法
str=str.substring(int beginIndex);截取掉str从⾸字母起长度为beginIndex的字符串,将剩余字符串赋值
substring和slice给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
dsWith(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);
}
}
补充:str=str.substring(int beginIndex,int endIndex);中最终得到的值:
beginIndex =< str的值 < endIndex
以上补充内容是我⾃⼰以前的⼀点理解
近⽇在API中看到对它的注解,
把它发布在下⾯以便更多的和我⼀样的初学者更好的理解上⾯的程序
substring
public  substring(int beginIndex,
int endIndex)
返回⼀个新字符串,它是此字符串的⼀个⼦字符串。该⼦字符串从指定的  beginIndex 处开始,⼀直到索引  endIndex - 1 处的字符。因此,该⼦字符串的长度为  endIndex-beginIndex。
⽰例:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
参数:
beginIndex - 开始处的索引(包括)。
endIndex - 结束处的索引(不包括)。
返回:
指定的⼦字符串。
抛出:
- 如果  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);}}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。