# 取一个字符串中长度为N，且头尾字符不存于字符串strTrim中的所有子串，请帮看看代码是否可以进一步优化？

ynduanlian 2018-02-07 05:02:56

str="ABCDEFGHI"
strTrim="AC"
N=4

BCDE
DEFG
EFGH
FGHI

``````
private ArrayList getSub1(string str,int n,string strTrim)
{
ArrayList arrRes = new ArrayList();
string strRes;
for (int i = 0; i <= str.Length - n; i++)
{//对字符串逐步扫描
StringBuilder sb = new StringBuilder();
for (int j = i; j < i + n ; j++)
{//输出扫描的起始点及以后的k个元素
sb.Append(str.Substring(j, 1));
}
strRes = sb.ToString();
if(!strRes.Equals(""))
{
if ((strTrim.IndexOf(strRes.Substring(0,1))<0) && (strTrim.IndexOf(strRes.Substring(strRes.Length-1,1))<0))
}
}
return arrRes;
}
``````
...全文
390 7 打赏 收藏 举报

7 条回复

ynduanlian 2018-02-10

• 打赏
• 举报

• 打赏
• 举报

• 打赏
• 举报

``````
private const int N = 4;
private List<string> getSubString(string str,string strTrim)
{
List<string> result = new List<string>();
StringBuilder sb = new StringBuilder();
char[] trim = strTrim.ToCharArray();

for (int i = 0; i < str.Length - N + 1; i++)
{
if (str[i] == trim[0] || str[i] == trim[1] || str[i + N - 1] == trim[0] || str[i + N - 1] == trim[1]) continue;

sb.Clear();
for (int j = i; j < N + i; j++)
{
sb.Append(str[j]);
}

}

return result;

}

private void Form5_Load(object sender, EventArgs e)
{
List<string> result = new List<string>();
string str = "ABCDEFGHI";
string strTrim = "AC";

System.Diagnostics.Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000000;i++ )
{
result = getSubString(str, strTrim);
}
sw.Stop();

listBox1.Items.Clear();
listBox1.Items.Add("Executed time is:" + sw.ElapsedMilliseconds.ToString() + "ms");
foreach(string s in result)
{
}
}

``````
• 打赏
• 举报

``HashSet<char> hash = new HashSet<char>(strTrim);``

• 打赏
• 举报

ynduanlian 2018-02-07

• 打赏
• 举报

xuzuning 2018-02-07
``````            string str = "ABCDEFGHI";
string strTrim = "AC";
int N = 4;
ArrayList arrRes = new ArrayList();
for (int i = 0; i < str.Length - (N - 1); i++)
{
if (strTrim.Contains(str[i]) || strTrim.Contains(str[i + N - 1])) continue;
}
foreach (var x in arrRes) Console.WriteLine(x);
``````
• 打赏
• 举报

C#

10.7w+

.NET技术 C#

2018-02-07 05:02