How to Read Substrings based on Length of the String in C#

前端 未结 5 1635
有刺的猬
有刺的猬 2021-01-23 16:06

I have a String which contains a substrings One of them is \"1 . 2 To Other Mobiles\" and other is \"Total\".Now as per my requirement i have to read the Contents between first

相关标签:
5条回答
  • 2021-01-23 16:57

    You may use String.LastIndexOf()

    0 讨论(0)
  • 2021-01-23 16:58

    You mean this?

    string currentText = "1 . 2 To Other Mobiles fkldsjkfkjslfklsdfjk  Total";
    string text = "1 . 2 To Other Mobiles";
    int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles");
    int endPosition = currentText.IndexOf("Total");
    string result = currentText.Substring(startPosition + text.Length, endPosition - (startPosition + text.Length));
    

    In the text "1 . 2 To Other Mobiles fkldsjkfkjslfklsdfjk Total";

    The output will be:

    fkldsjkfkjslfklsdfjk

    0 讨论(0)
  • 2021-01-23 17:06

    I have to read after the startPosition length to last position length

    Use LastIndexOf:

    string search1 = "1 . 2 To Other Mobiles";
    string search2 = "Total";
    
    int startPosition = currentText.IndexOf(search1);
    if(startPosition >= 0)
    {
        startPosition += search1.Length;
        int endPosition = currentText.LastIndexOf(search2);
        if (endPosition > startPosition)
        {
            string result = currentText.Substring(startPosition, endPosition - startPosition);
        }
    }
    

    What should i do if i need to read for the first "Total" only.

    then use IndexOf instead:

    // ...
    int endPosition = currentText.IndexOf(search2);
    if (endPosition > startPosition)
    {
        string result = currentText.Substring(startPosition, endPosition - startPosition);
    }
    
    0 讨论(0)
  • 2021-01-23 17:06

    Problem : you are not adding the length of the first search string 1 . 2 To Other MobilessubstringTotal

    Solution :

    string currentText = "1 . 2 To Other MobilessubstringTotal";
    string search1="1 . 2 To Other Mobiles";
    string search2="Total";
    int startPosition = currentText.IndexOf(search1);
    int endPosition = currentText.IndexOf(search2);
    string result = currentText.Substring((startPosition+search1.Length), endPosition - (startPosition+search1.Length));
    

    Output:

    result => substring

    0 讨论(0)
  • 2021-01-23 17:10

    try this.

    int startPosition = currentText.IndexOf("1 . 2 To Other Mobiles");
    int endPosition = currentText.LastIndexOf("Total") + 5;
    string result = currentText.Substring(startPosition, endPosition - startPosition);
    
    0 讨论(0)
提交回复
热议问题