C++ compose string in one line to give as parameter - c++

In my program I have a program that takes a std::string as parameter. When I call this function I want to give it a large (about 5) composition of strings. Is there a native toString() function that can spit out strings#? Can it be done on one line?
What I want:
std::string a = "sometext";
std::string b = "someothertext";
somefunction(ToString(a+b+"text"));

This works aswell:
std::string a = "sometext";
std::string b = "someothertext";
somefunction(a + b + "text");

std::string already has a operator+ that will concatenate strings. If you have
void foo(std::string some_name) { code in here }
And you want to pass it a combination of a bunch of string you can just use
foo(some_string + another_string + "some text" + even_another_string);
If all of your strings that you want to pass a literal strings then you will either have to add the custom string literal to one of them or convert one to a string
foo("this is a string"s + "another string" + "some more text");
//or
foo(std::string("this is a string") + "another string" + "some more text");

Related

How to convert a string to array of strings made of characters in c++?

How to split a string into an array of strings for every character? Example:
INPUT:
string text = "String.";
OUTPUT:
["S" , "t" , "r" , "i" , "n" , "g" , "."]
I know that char variables exist, but in this case, I really need an array of strings because of the type of software I'm working on.
When I try to do this, the compiler returns the following error:
Severity Code Description Project File Line Suppression State
Error (active) E0413 no suitable conversion function from "std::string" to "char" exists
This is because C++ treats stringName[index] as a char, and since the array is a string array, the two are incopatible.
Here's my code:
string text = "Sample text";
string process[10000000];
for (int i = 0; i < sizeof(text); i++) {
text[i] = process[i];
}
Is there any way to do this properly?
If you are going to make string, you should look at the string constructors. There's one that is suitable for you (#2 in the list I linked to)
for (int i = 0; i < text.size(); i++) {
process[i] = string(1, text[i]); // create a string with 1 copy of text[i]
}
You should also realise that sizeof does not get you the size of a string! Use the size() or length() method for that.
You also need to get text and process the right way around, but I guess that was just a typo.
std::string is a container in the first place, thus anything that you can do to a container, you can do to an
instance of std::string. I would get use of the std::transform here:
const std::string str { "String." };
std::vector<std::string> result(str.size());
std::transform(str.cbegin(), str.cend(), result.begin(), [](auto character) {
return std::string(1, character);
});

Writing normal C++ String to Rapid JSON is resulting in string with backslash

string str = {"appId":"com.mymusic.app","Connectivity":True,"DistractionLevel":2,"display":True};
if(!str.empty())
{
StringBuffer bf;
PrettyWriter<StringBuffer> writer (bf);
writer.StartObject();
writer.Key("info"));
writer.String(str.c_str());
writer.EndObject();
cout<<"request string is:" , (char *)bf.GetString());
}
cout is printing the below line with back slash
{"info":"\"appId\":\"com.mymusic.app\",\"checkConnectivity\":True,\"driverDistractionLevel\":2,\"display\":True}"}
What i was expecting is
{"info": {"appId":"com.mymusic.app","Connectivity":True,"DistractionLevel":2,"display":True} }
You are using the the wrong function. The String function will add a string value to the json-object and in this context the escaping of " to \" is expected.
I think what you actually want to do is add the string as a json-sub-object. From what I found in the rapidjson documentation the function you want to use for that is RawValue.

Get struct from line parsing

does anybody know how to get struct from line? For example, i have struct:
struct Variable {
Variable(){}
string m_name = "";
uint_16 value = 0;
string comments = "";
}
And some variants of line:
string line = "foo 0x22 #Comments"; //hex value
or
string line = "foo 222 #Comments"; //decimal value
or
string line = "foo ((1<4)&2) #Comments"; //expression value
or
string line = "foo ((1<4)&2)"; //without comment
The question is, should i use syntax analysis? Thanks.
Assuming all your fields are separated by a common delimiter (And that I've understood your question correctly), just break up the input string at the delimiters and consume them with string conversion functions. something like:
Variable parseVariable(const std::string& line)
{
Variable variable;
// You must define 'split'
std::vector<std::string> inputFields = split(line, " ");
variable.m_name = inputFields[0];
// You must also define 'convertStringToUint16'
variable.value = convertStringToUint16(inputFields[1]);
if(inputFields.size() > 2)
{
variable.comments = inputFields[2];
}
return variable;
}
Disclaimer: this code has not been tested
Now, regarding your use of the term "expression" I am worried that you may want to be able to evaluate arbitrary expressions for the value variable. If so, I recommend you define a VERY small scope of expressions that can be evaluated, as even simple mathematical expressions require decent work to process correctly.

C++ read select parts of std::string

I have been trying to extract only "Apple" from the string below ie. between "," and "/". Is there a way to extract the string between the delimters? Currently, all of the string after the "," is extracted.
std::string test = "Hello World, Apple/Banana";
std::size_t found;
found = test.find(",");
std::string str3 = test.substr(found);
std::cout << str3 << std::endl;
One step at a time. First, extract the part after the comma. Then extract the part before the following slash.
Alternatively, substr() also takes an optional 2nd parameter, the maximum number of characters to extract, instead of extracting everything that's left of the string. So, if you compute how many characters you want to extract, you can also do it in a single substr() call.
The first part is finding where the substring "Apple" begins. You can use find() for that. It returns the location of the first character of the substring. You can then use the std::string constructor to pass in the original string with start and stop locations.
References
String find(),
String constructor
std::string extractedString = std::string(test, test.find("Apple"), sizeof("Apple") - 1);
You can use the second argument of substr to find the length of the extraction
#include <string>
using namespace std;
int main(int argc, char * argv[]){
string test = "Hello World, Apple/Banana";
size_t f1 = test.find(',');
size_t f2 = test.find('/');
string extracted = test.substr(f1, f2 - f1);
}
This will output , Apple when using VC2013. If you change f1 to size_t f1 = test.find(',') + 2; it will output Apple.

Efficiency of passing a combined string as an argument

I want to call a function with an argument, which is a constructed string. For example:
std::string str = "data";
// ...
debug("we have " + str + " and it's good");
ideone link.
As far as I know, it creates a string in the first concatenation, and then creates a new one in the second concatenation, which means two inevitable allocations.
Is the following code more performant?
std::string str = "data";
// ...
debug(std::string("we have ") += str += " and it's good");
Or is the first code being optimized by the compiler to something similar?