Managing Strings In C++ - 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;
}

Related

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';
}

Splitting a string into an array of characters using a variable for the string

I'm trying to split a string into an array of individual characters. However, I would like the string to be input by the user, for which I need to define the string using a variable.
My question is, why does this work:
#include <iostream>
using namespace std;
int main() {
char arr [] = {"Giraffe"};
cout << arr[0];
return 0;
}
But this doesn't?
#include <iostream>
using namespace std;
int main() {
string word;
word = "Giraffe";
char arr [] = {word};
cout << arr[0];
return 0;
}
Thanks
Your example doesn't work because you're trying to put a std::string into an array of char. The compiler will complain here because std::string has no type conversion to char.
Since you're just trying to print the first character of the string, just use the array accessor overload of std::string, std::string::operator[] instead:
std::string word;
word = "Giraffe";
std::cout << word[0] << std::endl;
In your second example, the type of word is a std::string and there are no default type conversions from std::string to the type char.
On the other hand, the first example works because it can be interpreted as an array of char (but actually its just c-style const char *).
If, for some reason, you would want to convert std::string into the c-style char array, you might want to try something like this...
#include <iostream>
#include <string>
#include <cstring>
int main(void)
{
std::string word;
word = "Giraffe";
char* arr = new char[word.length() + 1]; // accounting for the null-terminating character
strcpy(arr, word.data());
std::cout << arr[0] << std::endl;
delete[] arr; // deallocating our heap memory
return 0;
}

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.

String erase-append

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

Random ascii char's appearing

I was trying to write a program that stores the message in a string backwards into a character array, and whenever I run it sometimes it successfully writes it backwards but other times it will add random characters to the end like this:
input: write this backwards
sdrawkcab siht etirwˇ
#include <iostream>
#include <string>
using namespace std;
int main()
{
string message;
getline(cin, message);
int howLong = message.length() - 1;
char reverse[howLong];
for(int spot = 0; howLong >= 0; howLong--)
{
reverse[spot] = message.at(howLong);
spot++;
}
cout << reverse;
return 0;
}
The buffer reverse needs to be message.length() + 1 in length so that it can store a null termination byte. (And the null termination byte needs to be placed in the last position in that buffer.)
Since you can't declare an array with a length that is only known at runtime, you have to use a container instead.
std::vector<char> reverse(message.length());
Or better, use std::string. The STL also offers some nice functions to you, for example building the reversed string in the constructor call:
std::string reverse(message.rbegin(), message.rend();
Instead of reversing into a character buffer, you should build a new string. It's easier and less prone to bugs.
string reverse;
for(howlong; howLong >= 0; howLong--)
{
reverse.push_back(message.at(howLong));
}
Use a proper C++ solution.
Inline reverse the message:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message;
getline(cin, message);
//inline reverse the message
reverse(message.begin(),message.end());
//print the reversed message:
cout << message << endl;
return 0;
}
Reverse a copy of the message string:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message, reversed_message;
getline(cin, message);
//reverse message
reversed_message = message;
reverse(reversed_message.begin(), reversed_message.end());
//print the reversed message:
cout << reversed_message << endl;
return 0;
}
If you really need to save the reversed string in a C string, you can do it:
char *msg = (char *)message.c_str();
but, as a rule of thumb use C++ STL strings if you can.