How to convert a string to array of strings made of characters in c++? - 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);
});

Related

How to get letter from String by index? C++

Can someone briefly explain how to get a character from index from String in C++.
I need to read the first 3 letters of a String and in java it would bestr.charAt(index) and I have been searching the internet for a solution for 2h now and still don't understand...
can some one please give me an example.
std::string provides operator[] to access a character by index:
https://en.cppreference.com/w/cpp/string/basic_string/operator_at
Example:
const std::string s("hello");
const char c = s[0];
// c is set to ‘h’
substr()
It returns a newly constructed string object with its value initialized to a copy of a substring of this object.
Syntax
substr(pos, pos+len)
Code
std::string str ("Test string"); //string declaration
string sub_string = str.substr(0,3);
String index starts from 0.
Best place to look would be cpluspluc.com: http://www.cplusplus.com/reference/string/string/
You may use as earlier mentioned: http://www.cplusplus.com/reference/string/string/operator[]/
std::string str ("Test string");
for (int i=0; i<str.length(); ++i)
{
std::cout << str[i];
}
Or better yet: http://www.cplusplus.com/reference/string/string/at/
std::cout << str.at(i);
which also checks for a valid position and throws an out of range exception otherwise.
Alternatively you could use http://www.cplusplus.com/reference/string/string/data/
to acces the raw data.
Or if you want to check that your string starts with a specific pattern: http://www.cplusplus.com/reference/string/string/rfind/
std::string str = "Hey Jude!";
if (str.rfind("Hey", 0) == 0) {
// match
}
Another option to obtain a single character is to use the std::string::at() member function. To obtain a substring of a certain length, use the std::string::substr member function.

Using regex_match() on iterator with string in c++

working on a c++ project, I need to iterate on a string ( or char* depending the solution you could provide me ! ). So basically I'm doing this :
void Pile::evalExpress(char* expchar){
string express = expchar
regex number {"[+-*/]"};
for(string::iterator it = express.begin(); it!=express.end(); ++it){
if(regex_match(*it,number)){
cout<<*it<<endl;
}
}
}
char expchar[]="234*+";
Pile calcTest;
calcTest.evalExpress(expchar);
the iterator works well ( I can put a cout<<*it<<'endl above the if statement and I get a correct output )
and then when I try to compile :
error: no matching function for call to 'regex_match(char&, std::__cxx11::regex&)'
if(regex_match(*it,number)){
^
I have no idea why this is happening, I tried to don't use iterator and iterate directly on the expchar[i] but I have the same error with regex_match()...
Regards
Vincent
Read the error message! It tells you that you're trying to pass a single char to regex_match, which is not possible because it requires a string (or other sequence of characters) not a single character.
You could do if (std::regex_match(it, it+1, number)) instead. That says to search the sequence of characters from it to it+1 (i.e. a sequence of length one).
You can also avoid creating a string and iterate over the char* directly
void Pile::evalExpress(const char* expchar) {
std::regex number {"[+-*/]"};
for (const char* p = expchar; *p != '\0'; ++p) {
if (regex_match(p, p+1, number)) {
cout<<*p<<endl;
}
}
}

Output partial string of a certain index of an array

C++ newbie here, I'm not sure if my title describes what I am trying to do perfectly, but basically I am trying to output one line of a string array for a certain index of that array.
For example: Say myArray[2] is the 3rd index of a string array, and it holds an entire paragraph, with each sentence separated by a newline character.
contents of myArray[2]: "This is just an example.
This is the 2nd sentence in the paragraph.
This is the 3rd sentence in the paragraph."
I would like to output only the first sentence of the content held in the 3rd index of the string array.
Desired output: This is just an example.
So far I have only been able to output the entire paragraph instead of one sentence, using the basic:
cout << myArray[2] << endl;
But obviously this is not correct. I am assuming the best way to do this is to use the newline character in some way, but I am not sure how to go about that. I was thinking I could maybe copy the array into a new, temporary array which would hold in each index a sentence of the paragraph held in the original array index, but this seems like I am complicating the issue too much.
I have also tried to copy the string array into a vector, but that didn't seem to help my confusion.
You can do something along these lines
size_t end1stSentencePos = myArray[2].find('\n');
std::string firstSentence = end1stSentencePos != std::string::npos?
myArray[2].substr(0,end1stSentencePos) :
myArray[2];
cout << firstSentence << endl;
Here's the reference documentation of std::string::find() and std::string::substr().
Below is a general solution to your problem.
std::string findSentence(
unsigned const stringIndex,
unsigned const sentenceIndex,
std::vector<std::string> const& stringArray,
char const delimiter = '\n')
{
auto result = std::string{ "" };
// If the string index is valid
if(stringIndex < stringArray.size())
{
auto index = unsigned{ 0 };
auto posStart = std::string::size_type{ 0 };
auto posEnd = stringArray[stringIndex].find(delimiter);
// Attempt to find the specified sentence
while((posEnd != std::string::npos) && (index < sentenceIndex))
{
posStart = posEnd + 1;
posEnd = stringArray[stringIndex].find(delimiter, posStart);
index++;
}
// If the sentence was found, retrieve the substring.
if(index == sentenceIndex)
{
result = stringArray[stringIndex].substr(posStart, (posEnd - posStart));
}
}
return result;
}
Where,
stringIndex is the index of the string to search.
sentenceIndex is the index of the sentence to retrieve.
stringArray is your array (I used a vector) that contains all of the strings.
delimiter is the character that specifies the end of a sentence (\n by default).
It is safe in that if an invalid string or sentence index is specified, it returns an empty string.
See a full example here.

C++ Converting Vector items to single String Error?

So I have a function, where KaylesPosition is a class with a vector<int> called piles:
// Produces a key to compare itself to equivalent positions
std::string KaylesPosition::makeKey(){
std::vector<int> temp(piles.size());
for (int i = 0;i<piles.size();i++){
temp[i]=piles[i];
}
std::sort (temp.begin(),temp.end());
std::string key = "" + temp.at(0);
for (int i=1 ; i<temp.size() ; i++){
key.push_back('.');
key.push_back(temp.at(i));
}
return key;
}
My expected output should be all of the elements in piles in order, separated by periods. However instead, I get key return as "_M_range_check". I have tried this using std::string.append() and I get either an empty string or a period. How do I get this function to return a string of all of the values in piles as expected?
The problem seems to be here:
key.push_back(temp.at(i));
You are trying to append an integer to a string without getting the string representation of the integer first. Try replacing that line with:
key += std::to_string(temp.at(i)); // This will only work if your compiler supports C++11
If your compiler doesn't support C++11, try this (don't forget to #include <sstream>):
std::ostringstream o;
o << temp.at(i);
key += o.str();
Or, if you have the option to use Boost (http://boost.org/ ), try its lexical_cast:
key += boost::lexical_cast<std::string>(temp.at(i));
The reason this code compiled in the first place, is because push_back accepts a char as its parameter and you're passing an int which gets converted to char (although I would expect a warning from the compiler in this case).
P.S.: Same applies for the line
std::string key = "" + temp.at(0);

How can I access a string like an array in AutoIt? (I'm porting code from C++ to AutoIt)

Ok, gah, syntax conversion issue here...How would I do this in AutoIt?
String theStr = "Here is a string";
String theNewStr = "";
for ( int theCount = 0; theCount < theStr.Size(); theCount++ )
{
theNewStr.Append(theStr[theCount]);
}
I am trying to access individual chars within a string in AutoIt and extract them. Thats's it. Thanks.
What about this:
$theStr = StringSplit("Here is a string", "") ; Create an array
$theNewStr = ""
For $i = 1 to $theStr[0] Step 1
$theNewStr = $theNewStr & $theStr[$i]
Next
MsgBox(0, "Result", $theNewStr)
#include <string>
std::string theStr = "Here is a string";
std::string theNewStr;
//don't need to assign blank string, already blank on create
for (size_t theCount = 0; theCount < theStr.Size(); theCount++ )
{
theNewStr += theStr[theCount];
}
//or you could just do
//theNewStr=theStr;
//instead of all the above
in autoit, it's just as simple to copy a string. to access a piece of a string (including a character, which is still a string) you use StringMid() which is a holdover from Microsoft BASIC-80 and now Visual BASIC (and all BASICs). you can stil do
theNewStr = theStr
or you can do it the hard way:
For $theCount = 1 to StringLen($theStr)
theNewStr &= StringMid($theStr, $theCount, 1)
Next
;Arrays and strings are 1-based (well arrays some of the time unfortunately).
& is concatenation in autoit. stringmid extracts a chunk of a string. it MIGHT also allow you to do the reverse: replace a chunk of a string with something else. but I would do unit testing with that. I think that works in BASIC, but not sure about autoit.