2015-11-02 84 views
-1
public static string shita1(string st1) 
    { 
     string st2 = "", stemp = st1; 
     int i; 
     for(i=0; i<stemp.Length; i++) 
     { 

      if (stemp.IndexOf("cbc") == i) 
      { 
       i += 2 ; 
       stemp = ""; 
       stemp = st1.Substring(i); 
       i = 0; 
      } 
      else 
       st2 = st2 + stemp[i]; 
     } 
     return st2; 
    } 




    static void Main(string[] args) 
    { 
     string st1; 
     Console.WriteLine("enter one string:"); 
     st1 = Console.ReadLine(); 
     Console.WriteLine(shita1(st1)); 
    } 


} 

我接到了我的大學一challange刪除一組字符,則challange是從字符串中移動任何「CBC」字......使用的indexOf(C#)從字符串

這是我的代碼......當我只使用一個「cbc」時,它可以工作,但是當我使用其中的2個時,它可以幫助... :)

+0

'string result = input.replace(「cbc」,string.Empty);'? –

回答

1

IndexOf方法爲您提供了一切您需要知道的信息。 按documentation

報告在此實例中首次出現指定的 Unicode字符或字符串的從零開始的索引。如果在此實例中未找到字符或字符串,則方法返回 -1。

這意味着只要返回的索引不是-1就可以創建一個重複的循環,而且您不必循環逐個字符串測試字符。

+0

那麼我如何從一個字符串中刪除多個「cbc」字符集呢? – atiafamily

+1

既然這是爲了學校,我會把你的具體細節留給你。但看看你已經知道了什麼。 1.如何找到「cbc」出現的位置。 2.如何知道什麼時候「cbc」不存在。 3.如何從字符串中刪除一組「cbc」。 4.如何循環。你已經擁有了你需要的所有工具。我相信你。 – Tofystedeth

0

我認爲這應該工作只是在一些例子測試它。不使用或與string.replace的IndexOf

 static void Main(string[] args) 
     { 
      Console.WriteLine("enter one string:"); 
      var input = Console.ReadLine(); 
      Console.WriteLine(RemoveCBC(input)); 
     } 

     static string RemoveCBC(string source) 
     { 
      var result = new StringBuilder(); 

      for (int i = 0; i < source.Length; i++) 
      { 
       if (i + 2 == source.Length) 
        break; 

       var c = source[i]; 
       var b = source[i + 1]; 
       var c2 = source[i + 2]; 

       if (c == 'c' && c2 == 'c' && b == 'b') 
        i = i + 2; 
       else 
        result.Append(source[i]); 
      } 

      return result.ToString(); 
     } 
0

您可以使用Replace刪除/替換字符串的所有出現另一個字符串內:

string original = "cbc_STRING_cbc"; 
original = original.Replace("cbc", String.Empty); 
+0

這將是最簡單的方法,但不符合指定的挑戰。 – Tofystedeth

0

如果你想刪除只使用的IndexOf從字符串中的字符方法你可以使用這段代碼。

public static string shita1(string st1) 
    { 
     int index = -1; 
     string yourMatchingString = "cbc"; 
     while ((index = st1.IndexOf(yourMatchingString)) != -1) 
      st1 = st1.Remove(index, yourMatchingString.Length); 
     return st1; 
    } 

此代碼移除您字符串的所有輸入。

但是你可以這樣做只是在同一行:

st1 = st1.Replace("cbc", string.Empty); 

希望這有助於。

相關問題