`
zhangminok
  • 浏览: 4946 次
社区版块
存档分类
最新评论

字符串的替换问题

 
阅读更多
如何替换指定位置的字符串(另附String类常用方法)2009-10-13 15:55
这里给出字符串的两个位置,pos1和pos2, 如何替换pos1和pos2之间的字串

答:用subString , String.substring(0,pos1)+newString+String.substring(pos2+1)

另附java字符串操作方法:

在JAVA语言中,字符串数据实际上由String类所实现的。Java字符串类分为两类:一类是在程序中不会被改变长度的不变字符串;二类是在程序中会被改变长度的可变字符串。Java环境为了存储和维护这两类字符串提供了 String和StringBuffer两个类。
一、创建字符串
例: String str=new("This is a String");

或者 String str="This is a String";

二、得到字符串对象的有关信息
1.通过调用length()方法得到String的长度.
例:

String str="This is a String";
int len =str.length();

2.StringBuffer类的capacity()方法与String类的 length()的方法类似,但是她测试是分配给StringBuffer的内存空间的大小,而不是当前被使用了的内存空间。
3.如果想确定字符串中指定字符或子字符串在给定字符串的位置,可以用 indexOf()和lastIndexOf()方法。

String str="This is a String";
Int index1 =str.indexOf("i");   //index=2
Int index2=str.indexOf('i',index+1);   //index2=5
Int index3=str.lastIndexOf("I");   //index3=15
Int index4=str.indexOf("String");  //index4=10


三、String 对象的比较和操作
1.String 对象的比较
String类的equals()方法用来确定两个字符串是否相等。

String str="This is a String";
Boolean result=str.equals("This is another String ");
//result=false


2.String对象的访问
A、方法charAt()用以得到指定位置的字符。

String str="This is a String";
char chr=str.charAt(3); //chr="i"


B、方法getChars()用以得到字符串的一部分字符串

public void getChars(int srcBegin,int srcEnd,char[]dst,int dstBegin)
String str="This is a String";
Char chr =new char[10];
Str.getChars(5,12,chr,0);  //chr="is a St"


C、subString()是提取字符串的另一种方法,它可以指定从何处开始提取字符串以及何处结束。
3.操作字符串
A、replace()方法可以将字符串中的一个字符替换为另一个字符。

String str="This is a String";
String str1=str.replace('T','t'); //str1="this is a String"


B、concat()方法可以把两个字符串合并为一个字符串。

String str="This is a String";
String str1=str.concat("Test"); //str1="This is a String Test"


C、toUpperCase()和toLowerCase()方法分别实现字符串大小写的转换。

String str="THIS IS A STRING";
String str1=str.toLowerCase(); //str1="this is a string";


D、trim()方法可以将字符串中开头和结尾处的空格去掉.

String str="This is a String   ";
String str1=str.trim();   // str1="This is a String"


E、String 类提供静态方法valueOf(),它可以将任何类型的数据对象转换为一个字符串。如

System.out.println(String,ValueOf(math,PI));


四、修改可变字符串
StringBuffer类为可变字符串的修改提供了3种方法,在字符串中间插入和改变某个位置所在的字符。
1.在字符串后面追加:用append()方法将各种对象加入到字符串中。
2.在字符串中间插入:用insert()方法。例

StringBuffer str=new StringBuffer("This is a String");
Str.insert(9,"test");
System.out.println(str.toString());


这段代码输出为:This is a test String
3.改变某个位置所在的字符,用setCharAt()方法。

Str.setCharAt(2,"k");
这个函数原形sb.setCharAt(int,char),注意第二个参数是char,你用双引号就成了字符串,应该使用单引号,即sb.setCharAt(2,'k');



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics