简体   繁体   中英

My code to find no. of a substrings in a string. Why is j<=str.length() - 3 causing runtime error?

    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        
        int T;
        int count = 0;                                      
        cin>>T;
        
        for(int i = 0; i<T; i++) 
        {
            
            string str;
            cin>>str;
            count = 0;

  • This part is for checking how many occurrences of "xyz" are there in my code.

  • The test conditon j<=str.length() - 3 in for loop is causing error for some test case(s).

  • When I run the for loop test condition j<=str.length() it does not give error.

     for(int j = 0;j<=str.length()-3; j++) { string x; x = str.substr(j, 3); if(x =="xyz") { count++; } } if(count) { cout<<count<<endl; } else { cout<<"-1"<<endl; } } return 0;

    }

String lengths use unsigned math; 2-3 becomes 2^64-1. Try j<-3 || j+3<=str.length() j<-3 || j+3<=str.length()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM