String erase-append - c++

So generally I am supposed to take a few first characters of a string and put them on the end of this string. To make it simple, let's say - first two characters. I tried something like this:
char a = mystring.at(0);
char b = mystring.at(1);
mystring.erase(0,1);
mystring.append(a);
mystring.append(b);
This of course gives an error converting from char to string. However, I have no idea how to do it, what other functions to use. Any ideas?

You can achieve this with the algorithm std::rotate:
#include <iostream>
#include <algorithm>
#include <string>
int main() {
std::string s = "ABCDEFGHIJ";
std::rotate(s.begin(), s.begin() + 2, s.end());
std::cout << s << std::endl;
}
Output:
CDEFGHIJAB

Related

Managing Strings In C++

So I make an array of string pointers and put a string in at position 0 of the array. If I don't know the length of the string in word[0] how do I find it? How do I then manage that string, because I want to remove the "_." and "." part of the string so I will be left with "apple Tree".How do I resize that string? (functions like strcpy,strlen, or string.end() didn't work, I get errors like "can't convert string to char*" etc)
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int counter=0;
string* word = new string[0];
word[0] = "apple_.Tree.";
return 0;
}
Edit:what i want to do is make a dynamic array of strings(not using vector) and then edit the strings inside
string is a class, so you can use its member functions to manage it. See the documentation.
To remove characters, use std::erase (see this answer).
#include <iostream>
#include <string>
#include <algorithm>
int main() {
// Create array of 10 strings
std::string array[10];
array[0] = "apple_.Tree.";
std::cout << array[0].size() << "\n";
array[0].erase(std::remove(array[0].begin(), array[0].end(), '.'), array[0].end());
array[0].erase(std::remove(array[0].begin(), array[0].end(), '_'), array[0].end());
std::cout << array[0];
return 0;
}

How to identify string is containing only number?

How to print only text in a string? I want to print only abc from.
string numtext = "abc123";
Here is the full code:
#include <stdio.h>
int main()
{
string text = "abc123";
if (text.matches("[a-zA-Z]") //get an error initialization makes integer from pointer without a cast
{
printf("%s", text);
}
getch();
}
My string contains both numbers and letters and I want to print letters only. But I get an error. What am I doing wrong?
First of all, there is no member function called std::string::matches available in the standard string library for this case.
Secondly, The title of the question does not match the question you have asked with the code. However, I will try to deal with both. ;)
How to print only text in a string?
You could simply print each element in the string(i.e. char s) if it is an alphabet while iterating through it. The checking can be done using the standard function called std::isalpha, from the header <cctype>. (See live example here)
#include <iostream>
#include <string>
#include <cctype> // std::isalpha
int main()
{
std::string text = "abc123";
for(const char character : text)
if (std::isalpha(static_cast<unsigned char>(character)))
std::cout << character;
}
Output:
abc
How to identify string is containing only number?
Provide a function which checks for all the characters in the string whether they are digits. You can use, standard algorithm std::all_of (needs header <algorithm> to be included) along with std::isdigit (from <cctype> header) for this. (See live example online)
#include <iostream>
#include <string>
#include <algorithm> // std::all_of
#include <cctype> // std::isdigit
#include <iterator> // std::cbegin, std::cend()
bool contains_only_numbers(const std::string& str)
{
return std::all_of(std::cbegin(str), std::cend(str),
[](char charector) {return std::isdigit(static_cast<unsigned char>(charector)); });
}
int main()
{
std::string text = "abc123";
if (contains_only_numbers(text))
std::cout << "String contains only numbers\n";
else
std::cout << "String contains non-numbers as well\n";
}
Output:
String contains non-numbers as well
You could use the find_last_not_of function of std::string and the create a substr
std::string numtext = "abc123";
size_t last_character = numtext.find_last_not_of("0123456789");
std::string output = numtext.substr(0, last_character + 1);
This solution just presumes that numtext always has a pattern of text+num, means something like ab1c23 would give output = "ab".
Using C++ standard regex for such scenarios is a good idea. You can customize a lot.
Below is a simple example.
#include <iostream>
#include <regex>
int main()
{
std::regex re("[a-zA-Z]+");
std::cmatch m;//TO COLLECT THE OUTPUT
std::regex_search("abc123",m,re);
//PRINT THE RESULT
std::cout << m[0] << '\n';
}

string s = "hello" vs string s[5] = {"hello"}

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s = "hello";
reverse(begin(s), end(s));
cout << s << endl;
return 0;
}
prints olleh
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s[5] = {"hello"};
reverse(begin(s), end(s));
cout << *s << endl;
return 0;
}
prints hello
Please help me understand why is such difference. I am newbie in c++, I am using c++ 11.
Ok, I corrected to s[5]={"hello"} from s[5]="hello" .
The first is a single string. The second is an array of five strings, and initializes all five string to the same value. However, allowing the syntax in the question is a bug (see the link in the comment by T.C.) and should normally give an error. The correct syntax would have the string inside braces, e.g. { "hello" }.
In the second program you are only printing one string of the five anyway, the first one. When you dereference an array, it decays to a pointer and gives you the value that pointer points to, which is the first element in the array. *s and s[0] are equivalent.
I think that what you are looking for is this:
int main() {
char s[] = "hello";
reverse(s, s + (sizeof(s) - 1));
cout << string(s) << endl;
return 0;
}
With char[6] you have an C-style string. Remember that theses strings must be terminated with '\0'. Therefore there is a 6th element.

Create a new string from prefix up to character position in C++

How can I find the position of a character in a string? Ex. If I input "abc*ab" I would like to create a new string with just "abc". Can you help me with my problem?
C++ standard string provides a find method:
s.find(c)
returns the position of first instance of character c into string s or std::string::npos in case the character is not present at all. You can also pass the starting index for the search; i.e.
s.find(c, x0)
will return the first index of character c but starting the search from position x0.
std::find returns an iterator to the first element it finds that compares equal to what you're looking for (or the second argument if it doesn't find anything, in this case the end iterator.) You can construct a std::string using iterators.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s = "abc*ab";
std::string s2(s.begin(), std::find(s.begin(), s.end(), '*'));
std::cout << s2;
return 0;
}
If you are working with std::string type, then it is very easy to find the position of a character, by using std::find algorithm like so:
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string first_string = "abc*ab";
string truncated_string = string( first_string.cbegin(), find( first_string.cbegin(), first_string.cend(), '*' ) );
cout << truncated_string << endl;
}
Note: if your character is found multiple times in your std::string, then the find algorithm will return the position of the occurrence.
Elaborating on existing answers, you can use string.find() and string.substr():
#include <iostream>
#include <string>
int main() {
std::string s = "abc*ab";
size_t index = s.find("*");
if (index != std::string::npos) {
std::string prefix = s.substr(0, index);
std::cout << prefix << "\n"; // => abc
}
}

Is there a quick way to check if a string is numeric?

Is it possible to check if a string variable is entirely numeric? I know you can iterate through the alphabets to check for a non-numeric character, but is there any other way?
The quickest way i can think of is to try to cast it with "strtol" or similar functions and see whether it can convert the entire string:
char* numberString = "100";
char* endptr;
long number = strtol(numberString, &endptr, 10);
if (*endptr) {
// Cast failed
} else {
// Cast succeeded
}
This topic is also discussed in this thread: How to determine if a string is a number with C++?
Hope this helps :)
#include <iostream>
#include <string>
#include <locale>
#include <algorithm>
bool is_numeric(std::string str, std::locale loc = std::locale())
{
return std::all_of(str.begin(), str.end(), std::isdigit);
}
int main()
{
std::string str;
std::cin >> str;
std::cout << std::boolalpha << is_numeric(str); // true
}
You can use the isdigit function in the ctype library:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
char mystr[]="56203";
int the_number;
if (isdigit(mystr[0]))
{
the_number = atoi (mystr);
printf ("The following is an integer\n",the_number);
}
return 0;
}
This example checks the first character only. If you want to check the whole string then you can use a loop, or if its a fixed length and small just combine isdigit() with &&.