如何在字符串中的字符之前找到 10 个字符?例如;
string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
如何在 X 之前找到 10 个字符?
如何在字符串中的字符之前找到 10 个字符?例如;
string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
如何在 X 之前找到 10 个字符?
string searchWithinThis = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
string searchForThis = "X";
int firstCharacter = searchWithinThis.IndexOf(searchForThis);
if (firstCharacter < 0) {
Console.WriteLine("Character {0} not found", searchForThis);
} else {
Console.WriteLine("First occurrence: {0}", firstCharacter);
}
如果您想要 X 之前的 10 个字符,包括 X:
int tenCharactersBefore = Math.Max(firstCharacter - 10, 0);
string result = searchWithinThis.SubString(tenCharactersBefore, 10)
Console.WriteLine("The ten characters before are {0}", result);
如果你想要 X 之前的 10 个字符的字符串,不包括 X:
int tenCharactersBefore = Math.Max(firstCharacter - 11, 0);
string result = searchWithinThis.SubString(tenCharactersBefore, 10)
Console.WriteLine("The ten characters before are {0}", result);
如果您只想要 X 之前 10 个字符的字符:
int tenCharactersBefore = Math.Max(firstCharacter - 10, 0);
string result = searchWithinThis.SubString(tenCharactersBefore, 1)
Console.WriteLine("The ten characters before are {0}", result);
您可以使用String.Substring
和String.IndexOf
方法,例如;
string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
Console.WriteLine(abcd.Substring(abcd.IndexOf("X") - 10, 10));
基本上,您获得该位置的索引X
并减去10
该位置,之后,您将获得从该位置开始的子字符串并在10
其后获取字符。
当然,您应该首先检查X
's 的索引是否大于10
或不大于。因为如果小于10,你应该检查;
if(abcd.IndexOf("X") < 10)
Console.WriteLine(abcd.Substring(0, abcd.IndexOf("X")));
else
Console.WriteLine(abcd.Substring(abcd.IndexOf("X") - 10, 10));
输出将是;
asdasasdss
这是一个DEMO
.
string result=string.Empty;
string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
int indexOfStringToSearch = abcd.IndexOf("X");
if(indexOfStringToSearch!=-1)
{
if(indexOfStringToSearch -10 >0)
result = abcd.Substring(indexOfStringToSearch-10,10);
else
result = abcd.Substring(0,indexOfStringToSearch-1);
}
如果只有一个“X”字符:
尝试这个:
string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
string[] words = s.Split('X');
Console.WriteLine(words[0].substring(words[0].length-10,10));
或多个
string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
string[] words = s.Split('X');
for(int i=0;i<words.length; i++)
{
Console.WriteLine(word[i].substring(word[i].length-10,10));
}