黑马程序员技术交流社区
标题:
貌似死循环了
[打印本页]
作者:
万大述
时间:
2013-6-26 11:40
标题:
貌似死循环了
想检测字符串中是否包含另一个字符串,并记录这些字符串的位置,在for循环中想跳过已检测的代码,就把条件变化写成了跳过已测字符串的量,结果测序运行,就在循环前后打印两个测试,结果“测试2”没有打印,代码如下,求指点。
string strs = "欢迎大家来到传智播客,成为传智.net工程师或java工程师!";
//string[] strArray = new string[strs.Length];
int[] position=new int[strs.Length];
Console.WriteLine("测试1");
for (int i = 0; i < strs.Length; i += position[i])
{
if (strs.Contains("传智"))
{
position[i] = i;
}
}
Console.WriteLine("测试2");
for (int j = 0; j < strs.Length; j++)
{
Console.WriteLine(position[j]);
}
Console.ReadKey();
作者:
chensc
时间:
2013-6-26 12:01
学习学习!
作者:
dongqinglove
时间:
2013-6-26 12:40
for (int i = 0; i < strs.Length;
i += position
)
{
if (strs.Contains("传智"))
{
position
= i;
}
}
这个循环写错了,你好好想想,在这个循环里i一直是0
作者:
y96352
时间:
2013-6-26 12:45
for (int i = 0; i < strs.Length; i += position
)
{
if (strs.Contains("传智"))
{
position
= i;
}
}
进入后 position
= i (i=0
然后i += position
i每次自增0 还是没变
你可以在 position
= i下面写个sw(i) 看看i的值是否改变了
作者:
菜鸟励志要逆袭
时间:
2013-6-26 13:09
在一个原字符串中查找一个特定的字符串是否存在。如果存在,会出现几次及出现的位置。
class Program
{
static void Main(string[] args)
{
string strs = "欢迎大家来到传智播客,成为传智.net工程师或java工程师!";
char[] myChar1 = strs.ToCharArray();
string str;
int[] j=new int[strs.Length];
Console.WriteLine("测试1");
Console.WriteLine("欢迎大家来到传智播客,成为传智.net工程师或java工程师!(输入上面这句话的一个活n个内容:)");
str = Console.ReadLine();
char[] myChar2 = str.ToCharArray();
for (int i = 0; i < myChar1.Length; i++)
{
if (myChar2[0] == myChar1[i])
{
if (str == strs.Substring(i, myChar2.Length))
{
Console.WriteLine("存在此字符");
j[i] = i;
Console.WriteLine("首字母位于原字符串中的第{0}位",j[i]);
continue;
}
else {
Console.WriteLine("不存在此字符");
break;
}
}
}
Console.ReadKey();
}
}
如有错误。望大神批评改正
作者:
万大述
时间:
2013-6-26 17:49
多谢各位朋友{:soso_e113:}
作者:
道法乾坤110
时间:
2013-6-26 17:57
你设置个断点,看看这段代码
for (int i = 0; i < strs.Length;
i += position
)
{
if (strs.Contains("传智"))
{
position
= i;
}
}
第一次循环,i=0,然后执行内部内容,然后把i赋给position,也就是此时position==0,执行完之后,然后就执行i+=position,也就是i=i+position,也就是i=i+0;也就是i==0, 这样下来,i就会一直是0
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2