大众信息网

实现String.replace()

关注:170  答案:6  手机版
解决时间 2021-02-21 11:24
实现String.replace()的功能。例如:原字符串为:I am a student, and I like sport. 将am替换成was,则替换后的字符串为:I was a student, and I like sport.
我的意思是要自己来实现String.replace()的功能,不是调用库函数
最佳答案
JAVA:

public class TestReplace {

public static void main(String[] args) {
String str="I am a student, and I like sport.";
str=str.replace("am","was");
System.out.println(str);
}
}
全部回答
str1=I am a student, and I like sport str2=str1.replace("am","was")
CString::Replace int Replace( TCHAR chOld, TCHAR chNew ); int Replace( LPCTSTR lpszOld, LPCTSTR lpszNew ); Return Value The number of replaced instances of the character. Zero if the string isn't changed. Parameters chOld The character to be replaced by chNew. chNew The character replacing chOld. lpszOld A pointer to a string containing the character to be replaced by lpszNew. lpszNew A pointer to a string containing the character replacing lpszOld. Remarks Call this member function to replace a character with another. The first prototype of the function replaces instances of chOld with chNew in-place in the string. The second prototype of the function replaces instances of the substring lpszOld with instances of the string lpszNew. The string may grow or shrink as a result of the replacement; that is, lpszNew and lpszOld do not have to be equal in length. Both versions perform case-sensitive matches. Example //First example, with old and new equal in length. CString strZap("C--"); int n = strZap.Replace('-', '+'); ASSERT(n == 2); ASSERT(strZap == "C++"); //Second example, old and new are of different lengths. CString strBang("Everybody likes ice hockey"); n = strBang.Replace("hockey", "golf"); ASSERT(n == 1); n = strBang.Replace("likes", "plays"); ASSERT(n == 1); n = strBang.Replace("ice", NULL); ASSERT(n == 1); ASSERT(strBang == "Everybody plays golf"); // note that you now have an extra space in your // sentence. To remove the extra space, include it // in the string to be replaced, i.e.,"ice ".
.net版 string str="I am a student, and I like sport."; string str2=str.Replace("am","was");
replace和replaceall是java中常用的替换字符的方法,它们的区别是: 1)replace的参数是char和charsequence,即可以支持字符的替换,也支持字符串的替换(charsequence即字符串序列的意思,说白了也就是字符串); 2)replaceall的参数是regex,即基于规则表达式的替换,比如,可以通过replaceall("\\d", "*")把一个字符串所有的数字字符都换成星号; 相同点是都是全部替换,即把源字符串中的某一字符或字符串全部换成指定的字符或字符串,如果只想替换第一次出现的,可以使用 replacefirst(),这个方法也是基于规则表达式的替换,但与replaceall()不同的是,只替换第一次出现的字符串; 另外,如果replaceall()和replacefirst()所用的参数据不是基于规则表达式的,则与replace()替换字符串的效果是一样的,即这两者也支持字符串的操作; 还有一点注意:执行了替换操作后,源字符串的内容是没有发生改变的.
你可以重写replace方法。 public static String replace(String a,String b){ a=b; }然后就可以在主函数中调用该方法
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!