[英]How to handle case-insensitive string replacement without using Regex in Java
這是CodingBat網站的一個問題。 我先把問題粘在一邊,然后討論我的努力:
給定兩個字符串base和remove,返回基本字符串的一個版本,其中刪除了刪除字符串的所有實例(不區分大小寫)。 您可以假設刪除字符串的長度為1或更長。 僅刪除不重疊的實例,因此使用“xxx”刪除“xx”會留下“x”。
withoutString("Hello there", "llo") → "He there" withoutString("Hello there", "e") → "Hllo thr" withoutString("Hello there", "x") → "Hello there"
這是我到目前為止寫的:
public String withoutString(String base, String remove) {
int len_b=base.length();
int len_r = remove.length();
String result="";
if(len_b<1 || len_r<1)
return "";
for (int i =0;i<=len_b-len_r;i++)
{
if(base.substring(i,i+len_r).equals(remove))
{
i=i+len_r-1;
}
else
{
result=result+base.substring(i,i+1);
}
}
if(!(base.substring(len_b-len_r+1, len_b).equals(remove)))
result=result+base.substring(len_b-len_r+1, len_b);
return result;
}
這會傳遞所有測試用例,除了刪除字符串不區分大小寫的情況。
例如: withoutString("This is a FISH", "IS") → "Th a FH"
我的代碼給了我“這是一個FH”,因為我在代碼中沒有處理區分大小寫。 我知道使用Regex可以在一行中完成。 我更感興趣的是知道在我現在的代碼中是否有辦法處理這些類型的測試用例。 另外,如果我的代碼更高效/更優雅,請告訴我。
String有一個equalsIgnoreCase(String s)
方法。
你可以使用equalsIgnoreCase
方法將此語句base.substring(i,i+len_r).equals(remove)
更改為base.substring(i,i+len_r).equalsIgnoreCase(remove)
。
希望有幫助。
public String withoutString(String base, String remove)
{
String str=base;
String str1=remove;
String str3=str;
int k=str1.length();
for(int i=0;i<(str.length()-k+1);i++)
{
if(str1.equalsIgnoreCase(str.substring(i, i+k)))
{
String str4=str.substring(i, i+k);
str3=str3.replaceFirst(str4,"" );
}
}
return str3;
}
我做到了沒有任何循環:)我想這不是最好的答案,但它的工作原理
public String withoutString(String base, String remove) {
String lastString = base.replace(remove, "");
remove = remove.toLowerCase();
String veryLastString = lastString.replace(remove, "");
remove = remove.toUpperCase();
String veryVeryLastString = veryLastString.replace(remove, "");
return veryVeryLastString;
}
public String withoutString(String base, String remove) {
String b=base.toLowerCase();
String r=remove.toLowerCase();
if(b.length()<r.length()) return base;
if(b.contains(r)) b=b.replaceAll(r,"");
String temp="";
int j=0;
for(int i=0;i<base.length();i++)
if(j<b.length()){
if(base.substring(i,i+1).equalsIgnoreCase(b.substring(j,j+1))){
temp+=base.substring(i,i+1);
j++;
}
}
return temp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.