How to determine a character within a string in c++ - 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 (i.e. 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.

Related

converting a string to a c string

m working on some homework but don't even know where to start on this one. If you could can you throw me in the right direction. This is what i'm suppose to do
Write your own version of the str_c function that takes a C++ string as an argument (with the parameter set as a constant reference variable) and returns a pointer to the equivalent C-string. Be sure to test it with an appropriate driver.
There are different possibilities to write such a function.
First, take a look at the C++ reference for std::string, which is the starting point for your problem.
In the Iterator section on that page, you might find some methods which can help you to get the string character by character.
It can also help to read the documentation for the std::string::c_str method, you'd like to imitate: string::c_string. It's important to understand, how the system works with normal C-strings (char*):
Due to the fact, that a C-string has now length- or size-attribute, a trick is used to determine the end of the string: The last character in the string has to be a '\0'.
Make sure you understand, that a char* string can also be seen as array of characters (char[]). This might help you, when understanding and solving your problem.
as we know, C-string is null-terminated array of char. you can put char by char from std::string to an array of char, and then closed with '\0'. and remember a pointer to a char (char*) is also representation of array of char. you can use this concept

Split and Assign char

I am new to C++ and Arduino.
I have 3 variable of type char
char receivePayload[31];
char devID;
char switchState;
the data in receivePayload woudl be some like "01:01" or "01:00". Here the first part before colon is device ID and second part is switchState.
Can you please help me and explain how I can split the 2. I did read about strtok but was unable to understand.
The desired output would be like
devID would have 01 stored and
switchState would have 01 or 00 stored.
Also if I can convert it into integer.
Thanks a ton.
As for your problem, there are multiple solutions to it: One is using std::getline as tokenizer. Another is using std::string::find and std::string::substr. Yet another solution is to use the old C function strtok.
The above solutions all give you strings, so either you have to make devId and switchState strings as well, or use e.g. std::stoi to convert the strings to integers.
Apparently the Arduino platform have neither of the functionality listed above, which mean you have to tokenize the string yourself. This is, however, very simple: Find the separator (the ':' character), copy from the beginning to (but not including) the separator into a temporary string and convert it to an integer with e.g. std::strtol. Then copy from (but not including) the separator into the temporary string and convert that value to an integer.
If you don't even have std::strtol then use std::atoi.
Since this is Arduino, you should probably use the String class since it handles a lot of the annoying stuff for you like conversion to int without having to explicitly link against glibc.
You could split the string like so:
String receivedPayload("01:10");
String devId = receivedPayload.substring(0, receivedPayload.indexOf(':'));
String switchState = receivedPayload.substring(receivedPayload.indexOf(':'));
Converting them into an integer would involve just using toInt on the string objects.
If you didn't need to convert into an integer, it would have been easier to tokenise the string yourself by using a for loop and checking if the character is equal to ':' since the string is so short.

Can regex be used with a character array in C++

I'm working on a program that cannot use the string library file, instead I am using char arrays. I am able to use regex, and was wondering if there is a way to use regex and character arrays, or even regex and a single char?
The reason why I ask is when I attempt to use my char array in a match the xUtility throws a bunch of errors from the "TEMPLATE CLASS iterator_traits"
if(regex_match(userCommand[3], userCommand[8], isNumeric))
errors:
std::regex_match and its friends work through iterators (as well as overloads for not only const std::string& but const char*).
So, yes, you can absolutely use a character array rather than std::string. I advise reading the documentation.
Per your edit:
if(regex_match(userCommand[3], userCommand[8], isNumeric))
If userCommand is the array, then you are passing in two chars, not pointers ("iterators").
Try:
if(regex_match(&userCommand[3], &userCommand[8], isNumeric))
or:
if(regex_match(userCommand + 3, userCommand + 8, isNumeric))

c++ best way to call function with const char* parameter type

what is the best way to call a function with the following declaration
string Extract(const char* pattern,const char* input);
i use
string str=Extract("something","input text");
is there a problem with this usage
should i use the following
char pattern[]="something";
char input[]="input";
//or use pointers with new operator and copy then free?
the both works but i like the first one but i want to know the best practice.
A literal string (e.g. "something") works just fine as a const char* argument to a function call.
The first method, i.e. passing them literally in, is usually preferable.
There are occasions though where you don't want your strings hard-coded into the text. In some ways you can say that, a bit like magic numbers, they are magic words / phrases. So you prefer to use constant identifier to store the values and pass those in instead.
This would happen often when:
1. a word has a special meaning, and is passed in many times in the code to have that meaning.
or
2. the word may be cryptic in some way and a constant identifier may be more descriptive
Unless you plain to have duplicates of the same strings, or alter those strings, I'm a fan of the first way (passing the literals directly), it means less dotting about code to find what the parameters actually are, it also means less work in passing parameters.
Seeing as this is tagged for C++, passing the literals directly allows you to easily switch the function parameters to std::string with little effort.

Overloading a method on default arguments

Is it possible to overload a method on default parameters?
For example, if I have a method split() to split a string, but the string has two delimiters, say '_' and "delimit". Can I have two methods something like:
split(const char *str, char delim = ' ')
and
split(const char *str, const char* delim = "delimit");
Or, is there a better way of achieving this? Somehow, my brain isn't working now and am unable to think of any other solution.
Edit: The problem in detail:
I have a string with two delimiters, say for example, nativeProbableCause_Complete|Alarm|Text. I need to separate nativeProbableCause and Complete|Alarm|Text and then further, I need to separate Complete|Alarm|Text into individual words and join them back with space as a separator sometime later (for which I already have written a utility and isn't a big deal). It is only the separation of the delimited string that is troubling me.
No, you cant - if you think about it, the notion of a default means 'use this unless I say otherwise'. If the compiler has 2 options for a default, which one will it choose?
How about implementing as 2 different methods like
split_with_default_delimiter_space
split_with_default_delimiter_delimit
Personally I'd prefer using something like this (more readable.. intent conveying) over the type of overloading that you mentioned... even if it was somehow possible for the compiler to do that.
Why not just call split() twice and explicitly pass the delimiter the second time? Will delimiters always be single characters?
Do you perform any other processing on the 2nd set of words before joining them? If not, then for the second task what you really want to do is replace substrings. This is most easily done with std::string::find and std::string::replace. If you must use c-strings, you could use strstr/strchr/strpbrk, strcpy and strcat, or use just strstr/strchr/strpbrk and join them in place.
You could use a version of split that accepts a variable number of delimiters (split(const char*,vector<string>), if you want to split(const char*, const char**)) or just use Boost Tokenizer.