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';
}
Related
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;
}
I have the following code which is part of a larger project. What this code is supposed to do is go through the line character by character looking for "tokens." The token I am looking for in this code is an ID. Which is defined as a letter followed by zero or more numbers or letters.
When a letter is detected it goes into the inner loop and loops through the next few characters, adding each character or letter to the idstring, until it finds the end of ID character(which is defined in the code) and then adds that idstring to a vector. At the end of the line it should output each element of the vector. Im not getting the output I need. I hope this is enough information to understand what is going on in the code. If someone could help me fix this problem I would be very great full. Thank you!
The output I need: ab : ab
What I get: a : a
#include <iostream>
#include <regex>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> id;
std::regex idstart("[a-zA-Z]");
std::regex endID("[^a-z]|[^A-Z]|[^0-9]");
std::string line = "ab ab";
//Loops character by character through the line
//Adding each recognized token to the appropriate vector
for ( int i = 0; i<line.length(); i++ )
{
std::string tempstring(1,line[i]);
//Character is letter
if ( std::regex_match(tempstring,idstart) )
{
std::string tempIDString = tempstring;
int lineInc = 0;
for ( int j = i + 1; j<line.length(); j++)
{
std::string tempstring2(1,line[j]);
//Checks next character for end of potential ID
if ( std::regex_match(tempstring2,endID) )
{
i+=lineInc+1;
break;
}
else
{
tempIDString+=tempstring2;
lineInc++;
}
}
id.push_back(tempIDString);
}
}
std::cout << id.at(0) << " : " << id[1] << std::endl;
return 0;
}
The question is 2.5 year old and now you will maybe laugh seeing it. You break; the inner for when finding the second charcter that matches and so you will never assign tempstring2 to tempstring1.
But let's forget about that code. There is no good design here.
You had a good idea to use std::regex, but you did not know, how it worked.
So lets have a look at the correct implementation:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <regex>
// Our test data (raw string). So, containing also \n and so on
std::string testData(
R"#( :-) IDcorrect1 _wrongID I2DCorrect
3FALSE lowercasecorrect Underscore_not_allowed
i3DCorrect,i4 :-)
}
)#");
std::regex re("(\\b[a-zA-Z][a-zA-Z0-9]*\\b)");
int main(void)
{
// Define the variable id as vector of string and use the range constructor to read the test data and tokenize it
std::vector<std::string> id{ std::sregex_token_iterator(testData.begin(), testData.end(), re, 1), std::sregex_token_iterator() };
// For debug output. Print complete vector to std::cout
std::copy(id.begin(), id.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
This does all the work in the definition of the variable and by calling the range constructor. So, a typical one-liner.
Hope somebody can learn from this code . . .
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
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 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 &&.