java replace字元替換函數的使用方法
replace(char oldChar, char newChar)
public class MainClass
{
public static void main( String args[] )
{
String s1 = new String( "hello" );
String s2 = new String( "GOODBYE" );
String s3 = new String( " spaces " );
System.out.printf( "s1 = %sns2 = %sns3 = %snn", s1, s2, s3 );
// test method replace
System.out.printf("Replace 'l' with 'L' in s1: %snn", s1.replace( 'l', 'L' ) );
} // end main
}
結果
s1 = hello
s2 = GOODBYE
s3 = spaces
Replace 'l' with 'L' in s1: heLLo
將空格換成 /
public class MainClass {
public static void main(String[] arg) {
String text = "To be or not to be, that is the question.";
String newText = text.replace(' ', '/'); // Modify the string text
System.out.println(newText);
}
}
結果
To/be/or/not/to/be,/that/is/the/question.
有朋友自己寫了一個replace函數
// 替換字串函數
// String strSource - 源字串
// String strFrom - 要替換的子串
// String strTo - 替換為的字串
public static String replace(String strSource, String strFrom, String strTo)
{
// 如果要替換的子串為空白,則直接返回源串
if(strFrom == null || strFrom.equals(""))
return strSource;
String strDest = "";
// 要替換的子串長度
int intFromLen = strFrom.length();
int intPos;
// 迴圈替換字串
while((intPos = strSource.indexOf(strFrom)) != -1)
{
// 擷取匹配字串的左邊子串
strDest = strDest + strSource.substring(0,intPos);
// 加上替換後的子串
strDest = strDest + strTo;
// 修改源串為匹配子串後的子串
strSource = strSource.substring(intPos + intFromLen);
}
// 加上沒有匹配的子串
strDest = strDest + strSource;
// 返回
return strDest;
}