2015-11-02 86 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); 

希望这有助于。