C#数组不同的索引
嗨,我想在字符串数组中搜索字符,但我需要在两个索引之间搜索。例如,在索引2和10之间。我该怎么做C#数组不同的索引,c#,C#,嗨,我想在字符串数组中搜索字符,但我需要在两个索引之间搜索。例如,在索引2和10之间。我该怎么做 foreach (var item in currentline[2 to 10]) { if (item == ',' || item == ';') { c++; break; } else { data += item; c++; } } 如您所见,foreach枚举集合或任何I
foreach (var item in currentline[2 to 10])
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
如您所见,
foreach
枚举集合或任何IEnumerable
正如注释所说,您可以使用for
循环,并选择所需的元素
或者,由于要搜索字符串中的字符,可以使用
IndexOf
,使用开始索引和计数查找字符所在的位置。由于在代码中没有使用c++
,因此我假设它是代码的一部分
您可以这样简单地添加您的问题:
- 在当前行中
- 将char从索引2取到10
- 直到你找到一个你不想要的字符
- 将结果字符数组连接到字符串
var data = "##";//01234567891 -- index for the string below.
var currentline= "kj[abcabc;z]Selected data will be between: '[]';";
var exceptChar = ",;";
data += new string(
input.Skip(3)
.Take(8)
.TakeWhile(x=> !exceptChar.Contains(x))
.ToArray()
);
您可以使用此LINQ解决方案搜索字符串中的字符并获取其索引:
string str = "How; are, you; Good ,bye";
char[] charArr = { ',', ';' };
int startIndex = 2;
int endIndex = 10;
var indexes = Enumerable.Range(startIndex, endIndex - startIndex + 1)
.Where(i=>charArr.Contains(str[i]))
.ToArray();
在这种情况下,我们得到
可枚举的.Range(2,9)
生成一个介于2和10之间的序列,而Where
子句过滤str
中与charArr
中的一个字符匹配的字符索引。有一个名为string的方法,允许您传递一个要搜索的字符数组、起始索引和计数。对于您的示例,您可以这样使用它:
string currentLine = ",;abcde;,abc";
int index = currentLine.IndexOfAny(new[] {',', ';'}, 2, 10-2);
Console.WriteLine(index);
请注意,最后一个参数是从指定索引开始搜索的字符数,因此如果要从索引2开始,从索引10结束,则计数将为
finish start
,即10-2
谢谢大家最后我用guid修复了它谢谢大家
myarr = new mytable[50];
number_of_records = 0;
number_of_records = fulllines.Length;
for (int line = 1; line < fulllines.Length; line++)
{
int c = 0;
for (int i = 0; i < record_lenth; i++)
{
string data = "";
string currentline = fulllines[line];
string value = "";
for (int x = c; x < fulllines[line].Length; x++)
{
value += currentline[x];
}
foreach (var item in value)
{
if (item == ',' || item == ';')
{
c++;
break;
}
else
{
data += item;
c++;
}
}
}
}
myarr=newmytable[50];
记录的数量=0;
记录的数量=整行。长度;
对于(int line=1;line
有一个正常的for循环,它允许你设置开始和结束索引位置,比如if-else之间的for(int i=2;i和setvar-item=currentline[i]
伪代码中的“c”是什么?@CodeNotFound不抱歉,我是错的。OP说“从索引2到10”,所以你是对的:D