set: how to list not strings starting with given string and ending with `/`?

后端 未结 3 937
忘掉有多难
忘掉有多难 2020-12-22 08:42

for example we have in our set:

 bin/obj/Debug/CloudServerPrototype/ra.write.1.tlog 
 bin/obj/Debug/CloudServerPrototype/rc.write.1.tlog 
 bin/obj/Debug/vc10         


        
3条回答
  •  盖世英雄少女心
    2020-12-22 09:10

    The easiest way I can think of, using the standard C functions, would be:

    char * string1 = "bin/obj/Debug"
    char * string2 = "bin/obj/Debug/CloudServerPrototype/rc.write.1.tlog"
    char result[64];
    // the above code is just to bring the strings into this example
    
    char * position = strstr(string1, string2);
    int substringLength;
    if(position != NULL){
        position += strlen(string2);
        substringLength = strchr(position, '/') - position;
        strncpy(result, position, substringLength);
    }else{
        strcpy(result, string1); // this case is for when your first string is not found
    }
    
    cout << result;
    

    The first thing that occurs, is finding the substring, string1, in the string we are analyzing, being string2. Once we found the starting point, and assuming it was there at all, we add the length of that substring to that starting point using pointer arithmatic, and then find the resulting string's length by subtracting the starting position from the ending position, which is found with strchr(position, '/'). Then we simply copy that substring into a buffer and it's there to print with cout.

    I am sure there is a fancy way of doing this with std::string, but I'll leave that to anyone who can better explain c++ strings, I never did manage to get comfortable with them, haha

提交回复
热议问题