How do I get a part of a string in C++? I want to know what are the elements from 0 to i.
You want to use std::string::substr. Here's an example, shamelessly copied from http://www.cplusplus.com/reference/string/string/substr/
// string::substr
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str="We think in generalities, but we live in details.";
// quoting Alfred N. Whitehead
string str2, str3;
size_t pos;
str2 = str.substr (12,12); // "generalities"
pos = str.find("live"); // position of "live" in str
str3 = str.substr (pos); // get from "live" to the end
cout << str2 << ' ' << str3 << endl;
return 0;
}
You use substr, documented here:
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string a;
cout << "Enter string (5 characters or more): ";
cin >> a;
if (a.size() < 5)
cout << "Too short" << endl;
else
cout << "First 5 chars are [" << a.substr(0,5) << "]" << endl;
return 0;
}
You can also then treat it as a C-style string (non-modifiable) by using c_str, documented here.
If the string is declared as an array of characters, you can use the following approach:
char str[20];
int i;
strcpy(str, "Your String");
// Now let's get the sub-string
cin >> i;
// Do some out-of-bounds validation here if you want..
str[i + 1] = 0;
cout << str;
If you mean std::string, use substr function as Will suggested.
Assuming you're using the C++ std::string class
you can do:
std::string::size_type start = 0;
std::string::size_type length = 1; //don't use int. Use size type for portability!
std::string myStr = "hello";
std::string sub = myStr.substr(start,length);
std::cout << sub; //should print h
use:
std::string sub_of_s(s.begin(), s.begin()+i);
which create a string sub_of_s which is the first i-th the element in s.
Related
I've got a problem with a program which finds all substring in a given string.
I've tried to make variable "found", which would contain a position of a previously found substring and then start searching from the position.
Here's my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
string str1;
cin >> str >> str1;
int i = 0;
int found = -1;
while(found < str1.size()){
found = str1.find(str, found + 1);
cout<<str1.find(str, found)<<endl;
i++;
}
}
for the following input: "ab
aabb"
it doesn't print anything.
Could you help?
So a little bit of theory first:
substr(a,b) -> returns cut out of the string from position a to position b
find(a) -> returns the position of found character or set of characters 'a'. returns -1 if NOT found.
Let's examine your code:
#include <iostream>
#include <string> //not really needed here. string should already be usable
using namespace std; //in small programs is ok but with big programs this could lead to problems with using specific things that could have the same names in std and other library. So its best to avoid this and or any other using namespace you use.
int main()
{
string str; // you should really name your variables better
string str1;
cin >> str >> str1; // your variable names are unreadable at first glance
int i = 0; // iterator cool but why is it needed if you're just using find()
int found = -1; // good variable although the name "pos" would probably be better as to further explain to the programmer what the variable does
while(found < str1.size()){ //not really sure what you were going for here
found = str1.find(str, found + 1); // this could have been your while logic above instead
cout<<str1.find(str, found)<<endl; // this finds the exact same position again using more resources. your variable found stores the position so doing cout << found << here would be better
i++;
}
}
Now let's see why your code doesn't show anything on console:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
string str1;
cin >> str >> str1; //you input ab as str and abbb as str1
int i = 0;
int found = -1;
while(found < str1.size()){ //first iteration is while(-1 < 4)
found = str1.find(str, found + 1); //<-- find needs just 1 parameter. heres your problem
cout<<str1.find(str, found)<<endl;
i++;
}
}
str1.find("ab); -> function find searches for "ab" in string str1. You don't need to add where it's meant to search for. Also the fact that your while loop is dependant on found < str1.size() and not anything to do with your iterator means your loop will go on forever. whenever this happens most IDE's crash your program giving you nothing cout'ed.
Fix:
#include <iostream>
using namespace std;
int main()
{
string str;
string str1;
int pos;
cin >> str >> str1;
for(int i = 0; i < str1.size(); i++) // this or could be while(true)
{
pos = str1.substr(i).find(str); //finds your string in the rest of the line
if (pos == -1)
{
//NOT FOUND
break; //stops
}
else
{
//FOUND
cout << pos + i << endl; //pos is position in the cut out after adding i we get global position
i += pos; // skip characters after we found them to NOT be found again
}
}
}
Another possible solution would be:
Walk the input string until the point you know the substring cannot fit anymore.
For each input string position, check if each substring starts with the substring (starts_with only since C++20).
[Demo]
#include <iostream>
#include <string>
int main() {
std::string str{ "ab aab" };
std::string sub{ "ab" };
int count{};
size_t last_index{ str.size() > sub.size() ? str.size() - sub.size() : 0 };
for (size_t i{0}; i <= last_index; ++i) {
if (str.substr(i).starts_with(sub)) {
count++;
}
}
std::cout << count;
}
// Outputs: 2
int find_substr(string substr, string str) {
int postion = 0;
auto beginning = str.c_str();
int i = 0;
char* p = (char *)beginning;
while (p && '\0'!=p)
{
p = strstr(p, substr.c_str());
if (!p)
break;
cout << "A substring is at index:" << p - beginning << "\n";
p++;
};
return 0;
}
void test()
{
string substr, str;
{
substr = "ab"; str = "aabb";
cout << "Finding " << substr << " in " << str << "\n";
find_substr(substr, str);
cout << "\n";
}
{
substr = "ab"; str = "abab";
find_substr(substr, str);
cout << "\n";
}
{
substr = "a"; str = "11111111111111111111111a";
find_substr(substr, str);
cout << "\n";
}
}
I have an assignment that wants me to get a cstyle string (just 1 word) from the user then use a function to reverse its letters. The function has to take in 2 parameters, the first that is the destination string, and the other that is the source string. It will take whatever is in the source string, reverse it, then store the reversed version in the second string.
But everytime I compile, I typed in hello it prints out: \370\365\277\357\376. I just learned how to use pointers and cstyle strings so I don't really know how to use them and I think thats what is messing up my code. I'm dont understand it that well though so I cant figure out where I'm going wrong at.
Please let me know if you know what I'm doing wrong. Thank you!
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
using namespace std;
void IsPalindrome(char *cstring);
void Reverse(char *str2[], char *str1[]);
int main() {
// user variables
char str1[81];
char reverse;
char str2[81];
strcpy (str2, str1);
//prompt user to input string
cout << "\nPlease input a string (80 chars max): ";
cin >> str1;
cout << "\nYour string is: " << str1 << endl;
//call function
Reverse(str2[81], str1[81]);
//Output reversed string
cout << "Your string reversed is: " << str2 << endl;
cout << "This is a " << "." << endl;
return 0;
}
void Reverse(char *str2, char *str1)
{
char* front, *rear;
int len = strlen(str1);
char temp;
front = str1;
rear = &str1[len - 1];
while(front < rear)
{
temp = *front;
*front = *rear;
*rear = temp;
front++;
rear --;
}
}
void IsPalindrome(char cstring)
{
}
Pointers make life harder, don't use them if you don't need them. As your assignment is to reverse a string, so just use string. string is const char* inside but it's much easier to handle.
Beside your problem with pointers and arrays in your code, you are getting your string from input using std::cin. Remember that this way you can't get strings that have white space one them (you will just get the first word).
Also there is some algorithm that do this kind of tasks for you these days but for educational reasons it's not bad to do it yourself.
Here is what you can do, in the code I mentioned places that you could use ready to use algorithms to do the task for you.
#include <iostream>
#include <cstring>
#include <string>
#include <cctype>
#include <algorithm>
void Reverse(std::string &inputStr);
int main()
{
// user variables
std::string str1 = "";
std::cout << "\nPlease input a string (80 chars max): ";
std::getline(std::cin, str1);
std::cout << "\nYour string is: " << str1 << std::endl;
Reverse(str1);
//You also can use stl algorithm to reverse string for you and don't do it manually like below, but as it is an assignment it would not be good
//std::reverse(str1.begin(), str1.end());
//Output reversed string
std::cout << "Your string reversed is: " << str1 << std::endl;
std::cout << "This is a " << "." << std::endl;
system("pause");
return 0;
}
void Reverse(std::string &str)
{
int n = str.length();
for(int i = 0; i < n / 2; i++)
{
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
//You also can use stl algorithm to do the swap for you like below
//std::swap(str[i], str[n - i - 1]);
}
}
NOTE: This example will reverse your original string that user entered, if you want to have the both original and reversed, you need to pass a copy of input to the function. something like this :
std::string str2(str1);
Reverse(str2);
std::cout << "Reversed : " << str2;
EDIT: To match your assignment requirements (have a function with two parameters and single word string) you can easily change the above code like this :
void Reverse(std::string inputStr, std::string &outputStr);
int main()
{
// user variables
std::string str1 = "";
std::string str2 = "";
std::cout << "\nPlease input a string (80 chars max): ";
std::cin >>str1;
std::cout << "\nYour string is: " << str1 << std::endl;
Reverse(str1, str2);
//You also can use stl algorithm to reverse string for you and don't do it manually like below, but as it is an assignment it would not be good
//std::reverse(str1.begin(), str1.end());
//Output reversed string
std::cout << "Your string original is: " << str1 << std::endl;
std::cout << "Your string reversed is: " << str2 << std::endl;
system("pause");
return 0;
}
void Reverse(std::string inputStr, std::string &outputStr)
{
outputStr = inputStr;
int n = outputStr.length();
for(int i = 0; i < n / 2; i++)
{
char temp = outputStr[i];
outputStr[i] = outputStr[n - i - 1];
outputStr[n - i - 1] = temp;
//You also can use stl algorithm to do the swap for you like below
//std::swap(str[i], str[n - i - 1]);
}
}
There is no need of using pointers for reversing a character array to another character array.
void Reverse(char *str2, char *str1)
{
int len = strlen(str1);
for(int n = 0; n< len; n++)
{
str2[n] = str1[len-n-1];
}
}
I need to convert a string in C++ to full upper case. I've been searching for a while and found one way to do it:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
transform(input.begin(), input.end(), input.begin(), toupper);
cout << input;
return 0;
}
Unfortunately this did not work and I received this error message:
no matching function for call to 'transform(std::basic_string::iterator, std::basic_string::iterator, std::basic_string::iterator,
I've tried other methods that also did not work. This was the closest to working.
So what I'm asking is what I am doing wrong. Maybe my syntax is bad or I need to include something. I am not sure.
I got most of my info here:
http://www.cplusplus.com/forum/beginner/75634/
(last two posts)
You need to put a double colon before toupper:
transform(input.begin(), input.end(), input.begin(), ::toupper);
Explanation:
There are two different toupper functions:
toupper in the global namespace (accessed with ::toupper), which comes from C.
toupper in the std namespace (accessed with std::toupper) which has multiple overloads and thus cannot be simply referenced with a name only. You have to explicitly cast it to a specific function signature in order to be referenced, but the code for getting a function pointer looks ugly: static_cast<int (*)(int)>(&std::toupper)
Since you're using namespace std, when writing toupper, 2. hides 1. and is thus chosen, according to name resolution rules.
Boost string algorithms:
#include <boost/algorithm/string.hpp>
#include <string>
std::string str = "Hello World";
boost::to_upper(str);
std::string newstr = boost::to_upper_copy("Hello World");
Convert a String In C++ To Upper Case
Try this small program, straight from C++ reference
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
#include <cctype>
using namespace std;
int main()
{
string s;
cin >> s;
std::transform(s.begin(), s.end(), s.begin(), std::ptr_fun<int, int>(std::toupper));
cout << s;
return 0;
}
Live demo
You could do:
string name = "john doe"; //or just get string from user...
for(int i = 0; i < name.size(); i++) {
name.at(i) = toupper(name.at(i));
}
Uppercase to Lowercase and viceversa using BitWise operators
1.
string s = "cAPsLock";
for(char &c: s)
c = c | ' '; // similar to: c = tolower(c);
cout << s << endl; // output: capslock
string s = "cAPsLock";
for(char &c: s)
c = c & ~' '; // similar to: c = toupper(c);
cout << s << endl; // output: CAPSLOCK
PS: for more info check this link
#include <iostream>
using namespace std;
//function for converting string to upper
string stringToUpper(string oString){
for(int i = 0; i < oString.length(); i++){
oString[i] = toupper(oString[i]);
}
return oString;
}
int main()
{
//use the function to convert string. No additional variables needed.
cout << stringToUpper("Hello world!") << endl;
return 0;
}
Like leemes said, you can use toupper(int). Like this:
void ToUpper(string &str) {
for (auto beg = str.begin(); beg != str.end(); ++beg) {
*beg = toupper(*beg);
}
}
It'll through in each character from str and convert it to upper. Example:
int main()
{
string name;
cout << "Insert a name: ";
cin >> name;
ToUpper(name);
cout << "Name in upper case: " << name << endl;
}
You can also use the function from code below to convert it to Upper-case.
#include<iostream>
#include<cstring>
using namespace std;
//Function for Converting Lower-Case to Upper-Case
void fnConvertUpper(char str[], char* des)
{
int i;
char c[1 + 1];
memset(des, 0, sizeof(des)); //memset the variable before using it.
for (i = 0; i <= strlen(str); i++) {
memset(c, 0, sizeof(c));
if (str[i] >= 97 && str[i] <= 122) {
c[0] = str[i] - 32; // here we are storing the converted value into 'c' variable, hence we are memseting it inside the for loop, so before storing a new value we are clearing the old value in 'c'.
} else {
c[0] = str[i];
}
strncat(des, &c[0], 1);
}
}
int main()
{
char str[20]; //Source Variable
char des[20]; //Destination Variable
//memset the variables before using it so as to clear any values which it contains,it can also be a junk value.
memset(str, 0, sizeof(str));
memset(des, 0, sizeof(des));
cout << "Enter the String (Enter First Name) : ";
cin >> str; //getting the value from the user and storing it into Source variable.
fnConvertUpper(str, des); //Now passing the source variable(which has Lower-Case value) along with destination variable, once the function is successfully executed the destination variable will contain the value in Upper-Case
cout << "\nThe String in Uppercase = " << des << "\n"; //now print the destination variable to check the Converted Value.
}
I want to ask for word from the user and then convert the word from string to char using 'strcpy'. Then I want to determine the sum of the ascii codes for all of the letters in the word.
However, I am having difficulties. I don't understand exactly how I can do that. This is what I have been able to do so far.
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
string word;
cout << "Enter word: ";
getline(cin, word);
/*
char w[word];
strcpy(w,word.c_str());
int ('A');
cout<<char(65);
*/
return 0;
}
The commented part is where I have been trying to do the converting. I copied the code from a worksheet. Even if it did work, I don't know how, and what it all means.
Thanks for your help.
char w[word];
strcpy(w, word.c_str());
char w[word] is incorrect. The square brackets is for the size, which must be a constant integral expression. word is of type std::string, so this makes neither logical nor practical sense. Maybe you meant it as:
char w = word;
But that still won't work because word is a string, not a character. The correct code in this case is:
char* w = new char[word.size() + 1];
That is, you allocate the memory for w using a char*. Then you use word.size() + 1 to initialize heap-allocated memory amounting to those bytes. Don't forget for the obligatory delete[] when you're finished using w:
delete[] w;
However, note that using raw pointers and explicit new is not needed in this case. Your code can easily be cleaned up into the following:
#include <numeric>
int main ()
{
std::string word;
std::getline(std::cin, word);
int sum = std::accumulate(word.begin(), word.end(), 0); /*
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
std::cout << "The sum is: " << sum << std::endl;
}
You don't need to use strcpy() (or use a char * at all, for that matter), but this'll do your counting using a char pointer:
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
const char * cword = word.c_str();
int ascii_total = 0;
while ( *cword ) {
ascii_total += *cword++;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}
Output:
paul#local:~/src/cpp/scratch$ ./asccount
Enter word: ABC
Sum of ASCII values of characters is: 198
paul#local:~/src/cpp/scratch$
If you really do want to use strcpy(), I'll leave it as an exercise to you to modify the above code.
Here's a better way to do it, just using std::string (and C++11, and obviously presuming your system uses the ASCII character set in the first place):
#include <iostream>
#include <string>
int main() {
std::string word;
std::cout << "Enter word: ";
std::cin >> word;
int ascii_total = 0;
for ( auto s : word ) {
ascii_total += s;
}
std::cout << "Sum of ASCII values of characters is: ";
std::cout << ascii_total << std::endl;
return 0;
}
This question already has answers here:
How do I iterate over the words of a string?
(84 answers)
Closed 9 years ago.
I am having problems splitting a string using pure C++
The string always looks like this
12344//1238
First int then // and then the second int.
Need help to get the two int values and ignore the //
string org = "12344//1238";
size_t p = org.find("//");
string str2 = org.substr(0,p);
string str3 = org.substr(p+2,org.size());
cout << str2 << " "<< str3;
why cant we use sscanf?
char os[20]={"12344//1238"};
int a,b;
sscanf(os,"%d//%d",a,b);
Reference
Take a look at the strtok function
This should Split and convert to integers:
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline double convertToInt(std::string const& s,
bool failIfLeftoverChars = true)
{
std::istringstream i(s);
int x;
char c;
if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
throw BadConversion("convertToInt(\"" + s + "\")");
return x;
}
int main()
{
std::string pieces = "12344//1238";
unsigned pos;
pos = pieces.find("//");
std::string first = pieces.substr(0, pos);
std::string second = pieces.substr(pos + 2);
std::cout << "first: " << first << " second " << second << std::endl;
double d1 = convertToInt(first), d2 = convertToInt(second) ;
std::cout << d1 << " " << d2 << std::endl ;
}
Simplest way I can think of:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
void main ()
{
int int1, int2;
char slash1, slash2;
//HERE IT IS:
stringstream os ("12344//1238");
os>> int1 >> slash1 >> slash2 >> int2;
//You may want to verify that slash1 and slash2 really are /'s
cout << "I just read in " << int1 << " and " << int2 << ".\n";
system ("pause");
}
Also nice because it's so easy to rewrite -- if, say, you decide to read in ints delimited by something else.
Take the integers in as a string.
The string will then have the numbers and the // symbols.
Next you can run a simple for loop looking for the '/' in the string.
The values prior to the symbol are stored in another string.
When '/' appears, the for loop will terminate. You now have the index of the first
'/' symbol.
Increment the index and copy the rest of the string using anothe for loop, in another
string.
Now you have two separate strings.