在角色前找到10个字符

时间:2013-05-25 17:51:59

标签: c#

如何在字符串中的字符前找到10个字符?例如;

string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";

如何在X之前找到10个字符?

4 个答案:

答案 0 :(得分:4)

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);

答案 1 :(得分:1)

您可以使用String.SubstringString.IndexOf等方法;

string abcd = "asdsdasdasdasdasdasasdasasdssXsdasdsadas";
Console.WriteLine(abcd.Substring(abcd.IndexOf("X") - 10, 10));

基本,你得到X的索引并用该位置减去10,之后,你得到从该位置开始的子串并得到10之后的人物。

当然,您应首先检查X的索引是否大于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

答案 2 :(得分:1)

 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);
     }

答案 3 :(得分:0)

如果只有一个'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));
}