C# third index of a character in a string

前端 未结 10 1949
甜味超标
甜味超标 2020-12-06 17:18

is there a command that can get the third index of a character in a string? For example:

error: file.ext: line 10: invalid command [test:)]

相关标签:
10条回答
  • 2020-12-06 17:53
    int pos = -1;
    for ( int k = 0; k < 3; ++k )
    {
      pos = s.indexOf( ':', pos+1 );
      // Check if pos < 0...
    }
    
    0 讨论(0)
  • 2020-12-06 17:54

    String.IndexOf will get you the index of the first, but has overloads giving a starting point. So you can use a the result of the first IndexOf plus one as the starting point for the next. And then just accumulate indexes a sufficient number of times:

    var offset = myString.IndexOf(':');
    offset = myString.IndexOf(':', offset+1);
    var result = myString.IndexOf(':', offset+1);
    

    Add error handling unless you know that myString contains at least three colons.

    0 讨论(0)
  • 2020-12-06 17:56

    Please see this answer on a similar question: https://stackoverflow.com/a/46460083/7673306
    It provides a method for you to find the index of nth occurrence of a specific character within a designated string.

    In your specific case it would be implemented like so:

    int index = IndexOfNthCharacter("error: file.ext: line 10: invalid command [test:)]", 3, ':');
    
    0 讨论(0)
  • 2020-12-06 17:58

    Simply split the string by the char. This gives you an array that you can then use to target what you want.

    var stringToSplit = "one_two_three_four";
    var splitString = stringToSplit.Split("_");          
    if (splitString.length > 3){
        var newString = $"{splitResult[0]}_{splitResult[1]}_{splitResult[2]}";
    }
    
    0 讨论(0)
  • 2020-12-06 18:01

    You could write something like:

        public static int CustomIndexOf(this string source, char toFind, int position)
        {
            int index = -1;
            for (int i = 0; i < position; i++)
            {
                index = source.IndexOf(toFind, index + 1);
    
                if (index == -1)
                    break;
            }
    
            return index;
        }
    

    EDIT: Obviously you have to use it as follows:

    int colonPosition = myString.CustomIndexOf(',', 3);
    
    0 讨论(0)
  • 2020-12-06 18:06

    I am guessing you want to parse that string into different parts.

    public static void Main() {
        var input = @"error: file.ext: line 10: invalid command [test (: ]";
        var splitted = input .Split(separator: new[] {": "}, count: 4, options: StringSplitOptions.None);
    
        var severity = splitted[0]; // "error"
        var filename = splitted[1]; // "file.ext"
        var line = splitted[2];     // "line 10"
        var message = splitted[3];  // "invalid command [test (: ]"
    }
    
    0 讨论(0)
提交回复
热议问题