How can I extract a substring in c++ of all the characters before a * character. For example, if I have a string
ASDG::DS"G*0asd}}345sdgfsdfg
how would I extract the portion
ASDG::DS"G
You certainly don't need a regular expression for that. Just use std::string::find('*') and std::string::substr:
#include <string>
int main()
{
// raw strings require C++-11
std::string s1 = R"(ASDG::DS"G*0asd}}345sdgfsdfg)";
std::string s2 = s1.substr(0, s1.find('*'));
}
I think your text doesn't have multiple * because find return with first *
#include <iostream>
#include <string>
using namespace std;
#define SELECT_END_CHAR "*"
int main(){
string text = "ASDG::DS\"G*0asd}}345sdgfsdfg";
unsigned end_index = text.find(SELECT_END_CHAR);
string result = text.substr (0,end_index);
cout << result << endl;
system("pause");
return 0;
}
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;
}
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';
}
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;
}
How can I parse a string that looks like "xxxx-xxxx" and get those xxxx parts as a number? For an example, the user will type in "9349-2341" and I will get those numbers as two different integers.
I need to do that for a random number generator, which chooses the number between these xxxx variables.
Thanks.
You can use std::stringstream to extract numbers from string. It looks like that:
std::stringstream str_stream;
std::string str_to_parse = "1234-5678";
int num[2];
str_stream << str_to_parse;
str_stream >> num[0];
str_stream.ignore(1); // otherwise it will extract negative number (-5678)
str_stream >> num[1];
Also, there is C functions, like sscanf(). For example, your pattern can be extracted with this format: "%d-%d".
std::string str = "1234-5678";
std::string str1 = str.substr (0,4);
std::string str2 = str.substr(5, 4);
int n1 = std::stoi(str1);
int n2 = std::stoi(str2);
// do your random number generation between n1 and n2
Using regular expression
If your input is assured to resemble "xxxx-xxxx" where 'x' represents a digit, you can simply ultilize the following function:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
string input = "9349-2341";
// This pattern matches any string begining with 4 digits and ending with 4 digits, both parts seperated by a slash
string pattern = "([0-9]{4})-[0-9]{4}";
smatch matcher;
regex prog (pattern);
if (regex_search(input, matcher, prog))
{
auto x = matcher[1];
cout << x << " " << endl;
input = matcher.suffix().str();
}
else
{
cout << "Invalid input!" << endl;
}
return 0;
}
As for how to convert string to number, check out this article, from which the following segment is quoted:
string Text = "456";//string containing the number
int Result;//number which will contain the result
stringstream convert(Text); // stringstream used for the conversion initialized with the contents of Text
if ( !(convert >> Result) )//give the value to Result using the characters in the string
Result = 0;//if that fails set Result to 0
//Result now equal to 456
Or, simply as followed:
Using sscanf
#include <cstdio>
using namespace std;
int main(int argc, char ** argv)
{
char input[] = "1234-5678";
int result, suffix;
sscanf(input, "%i-%i", &result, &suffix);
printf("Output: '%i-%i'.\n", result, suffix);
return 0;
}
You should check out C++ reference websites, such as CPlusPlus.
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
}
}