简体   繁体   中英

How to determine a character within a string in c++

I have a variable named "String" that may have values like the following ones:

const char* String = "/v1/AUTH_abb52a71-fc76-489b-b56b-732b66bf50b1/test/DSC_0188.JPG";

or

const char* String = "/auth/v1.0";

or

const char* String = "/v2/AUTH_abb52a71-fc76-489b-b56b-732b66bf50b1/images?limit=1000&delimiter=/&format=xml";

Now I want to make sure whether or not "String" has the character 'v1'. Checking this has to be precise. I tried with strchr, but it's not quite accurate as it doesn't take 'v1' as one character, it rather takes 'v' and '1' as two separate characters. Moreover I can't use namepace std and library string, I can only use "string.h". Within these limitations how can I accurately check whether the variable "String" has a character 'v1'?

Thank you.

I want to make sure whether or not "String" has the character 'v1'

I can only use "string.h"

Then you probably want strstr . Also v1 is not a character, it's a string.


Side note: why use cstring in C++ ? What kind of teacher is still calling it string.h ?!

v1 is not character according to any alphabet. This is a proper string "v1" and as @cnicutar mentioned the c way to search for string in string is to use strstr . It is quite easy to use and runs KMP which is also very fast (though for the kind of your string it is not that crucial).

I would advise you to:

  • always name your variables starting small-caps (ie String -> my_string )
  • declare your string as const char[] , no need to interfere with pointers, when you can avoid them. Declaring this as pointer might confuse you, that you dynamically allocated the memory for the string.

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