How can I get :
connect
100
username
example
from this string:
ngg://connect>100/username>example/
Using std::string::find with arguments "/" and ">" and std::string::substr with the found indexes.
This is a good start.
Adding an answer with strtok for the sake of diversity:
char str[] = "ngg://connect>100/username>example/";
char *s = strtok(str, ">/");
std::vector<std::string> tokens;
while (s = strtok(NULL, ">/"))
tokens.push_back(std::string(s));
This will split the string str into the desired tokens (discarding the first ngg:, like in the question).
Here's a working example of this code.
A possibility is boost::split():
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
int main()
{
std::vector<std::string> tokens;
std::string s("ngg://connect>100/username>example/");
boost::split(tokens, s, boost::is_any_of("/>"));
// "connect" == tokens[2]
// "100" == tokens[3]
// "username" == tokens[4]
// "example" == tokens[5]
return 0;
}
ngg://connect>100/username>example/
If this format is fixed, then you can use std::sscanf as:
#include <iostream>
#include <cstdio>
int main()
{
char const *input = "ngg://connect>100/username>example/";
char const *input_format = "ngg://%[^>]>%d/%[^>]>%[^/]";
char connect[100], user[100], str[100]; //assuming max size is 100
int num;
if ( std::sscanf(input, input_format, connect, &num, user, str) != 4 )
{
std::cerr<<"error - number of tokens read must be equal to 4";
return 0;
}
std::cout << connect <<std::endl;
std::cout << num <<std::endl;
std::cout << user <<std::endl;
std::cout << str <<std::endl;
}
Output (online demo):
connect
100
username
example
Related
We have a char. We need to replace all ab characters from our char with the letter c.
Example we have :
abracadabra
the output will be :
cracadcra
I tried to use replace() function from C++, but no success.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string test;
cin>>test;
for(int i=0;i<(strlen(test)-1);i++)
{
if((test[i]=='a')&&(test[i+1]=='b')){
test.replace( test[i], 'c' );
test.replace( test[i+1] , ' ' );
}
}
cout << test << endl;
return 0;
}enter code here
You can use C++11 regex:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "abracadabra";
std::regex r("ab");
std::cout << std::regex_replace(str, r, "c") << "\n"; // cracadcra
}
Problem:
That is not the syntax of std::string::replace.
Solution:
As is mentioned here the syntax is std::string::replace(size_t pos, size_t len, const string& str). Do test.replace(i, 2, "c" ) instead of test.replace(test[i],'c').
Or use regular expressions as dtell pointed.
Adittional information:
using namespace std; is considered a bad practice (More info here).
You should use std::string::size instead of strlen when you're working with std::string.
To work with std::string you should use #include <string> instead of #include <cstring>.
Full code:
#include <iostream>
int main()
{
std::string test;
std::cin >> test;
for(unsigned int i = 0; i < test.size() - 1; i++)
{
if((test[i]=='a') && (test[i+1]=='b'))
{
test.replace(i, 2, "c" );
}
}
std::cout << test << std::endl;
return 0;
}
The simplest thing you can do by using the standard library is first to find ab and then replace it. The example code I wrote is finding string ab unless there is None in the string and replacing it with c.
#include <iostream>
#include <string>
int main()
{
std::string s = "abracadabra";
int pos = -1;
while ((pos = s.find("ab")) != -1)//finding the position of ab
s.replace(pos, sizeof("ab") - 1, "c");//replace ab with c
std::cout << s << std::endl;
return 0;
}
//OUTPUT
cracadcra
I want to remove a character ('#') from a string,
I tried to check if the string has '#' with the find function, which it does, then erase this with the erase function.
For some reason I get a run time error that says I have no memory.
Error: std::out_of_range at memory location 0x003BF3B4
#include <iostream>
#include <algorithm>
#include <string>
int main()
{
std::string str = "Hello World#";
if (str.find('#')) {
str.erase('#');
}
return 0;
}
The excepted output is: "Hello World"
Try something like this:
#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), '#'), str.end());
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s = "Hello World#";
char c = '#';
/* Removing character c from s */
s.erase(std::remove(s.begin(), s.end(), c), s.end());
std::cout << "\nString after removing the character "
<< c << " : " << s;
}
If you want to delete all '#' from the string:
std::string str = "Hello World#";
std::size_t pos = str.find('#');
while(pos != std::string::npos)
{
str.erase(pos, 1); //<- edited here
pos = str.find('#');
}
cout << str;
I want to reverse a string without the use of a loop. My code with the loop looks like:
#include <iostream>
#include <string>
using namespace std;
string reverseString(string str) {
string changedString;
int strLength = int(str.length() - 1);
for(int i {strLength}; i >= 0; i--) {
changedString.push_back(str.at(i));
}
return changedString;
}
int main() {
string str;
cout << "Enter a string to reverse it:\n" << flush;
cin >> str;
cout << reverseString(str) << flush;
}
Now I need to write a function without the loop. Only the methods of String should be used. Can you help me solving this problem?
It is very simple to write such a function
std::string reverse( const std::string &s )
{
return { s.rbegin(), s.rend() };
}
Here is a demonstrative program
#include <iostream>
#include <string>
std::string reverse( const std::string &s )
{
return { s.rbegin(), s.rend() };
}
int main()
{
std::string s( "Hello World" );
std::cout << s << '\n';
std::cout << reverse( s ) << '\n';
return 0;
}
Its output is
Hello World
dlroW olleH
Well, you can do that using recursion. Here are some links if you aren't aware what recursion is : link1 and link2.
Technically it won't be a loop.
string reverseString(string str, int index, string ans) {
if (index == -1) return ans;
ans += str[index];
return reverseString(str, index - 1, ans);
}
Parameters for this function will be str as it was by default, index = size(str) - 1 and ans ans = "";
reverseString(str, size(str) - 1, "") for example.
If you want your function to take exactly one argument, then you can write wrapper function and the one I wrote will have different name - reverseStringWrapper for example and in reverseString there will be only one line - return reverseStringWrapper(str, size(str) - 1, "");
string reverseStringWrapper(string str, int index, string ans) {
if (index == -1) return ans;
ans += str[index];
return reverseString(str, index - 1, ans);
}
string reverseString(string str) {
return reverseStringWrapper(str, size(str) - 1, "");
}
How was this?
In c, You can use strrev() function to reverse the string(char*)
In c++, you can either use std::reverse() or StringBuilder.reverse()
method to reverse a string.
.
This way you can reverse the char array(char*).
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
// Function to reverse a given character array using std::reverse
void reverse(char *str)
{
std::reverse(str, str + strlen(str));
}
// main function
int main()
{
/* using C string */
char s[] = "Hello World";
reverse(s);
cout << "Reverse of the given string is : " << s;
return 0;
}
This way you can reverse the string.
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
// Function to reverse a given character array using std::reverse
void reverse(char* str)
{
std::reverse(str, str + strlen(str));
}
// main function
int main()
{
/* using C string */
// char s[] = "Techie Delight";
string s = "hello world";
int n = s.length();
// declaring character array
char char_array[n + 1];
// copying the contents of the
// string to char array
strcpy(char_array, s.c_str());
reverse(char_array);
s = char_array;
cout << "Reverse of the given string is : " << s;
return 0;
}
Hope this might Helps:)
How can I change all \ to \\?
I want to make address to work with files:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "C:\\user\\asd";
replace(str.begin(), str.end(), '\\', '\\\\');
cout << str;
return 0;
}
I am getting an error:
F:\c++\tests\regex\main.cpp|8|error: no matching function for call to 'replace(std::basic_string<char>::iterator, std::basic_string<char>::iterator, char, int)'|
How can I do this work with a char array in C++ (without a function)?
You are using std::replace(), which replaces values within a range of iterators. In this situation, you are using iterators from a std::string, so the value being searched for, and the value to replace it with, must both be single char values. However, '\\\\' is a multi-byte character, and thus can't be used as a char value. That is why you are getting the compiler error.
std::string has its own overloaded replace() methods, several of which can replace portions of the std::string with multi-character strings.
Try this instead, eg:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "C:\\user\\asd";
string::size_type pos = 0;
while ((pos = str.find('\\', pos)) != string::npos)
{
str.replace(pos, 1, "\\\\");
pos += 2;
}
cout << str;
return 0;
}
Live demo
However, you say you "want to make address to work with files", which implies to me that you want to create a file: URI. If so, then you need something more like this instead (this is a gross over-simplification, a proper URI generator would be more complex then this, as URIs have many rules to them, but this will get you started):
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
const char* safe_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~!$&'()*+,;=:#/";
int main()
{
string str = "C:\\user\\ali baba";
replace(str.begin(), str.end(), '\\', '/');
string::size_type pos = 0;
while ((pos = str.find_first_not_of(safe_chars, pos)) != string::npos)
{
ostringstream oss;
oss << '%' << hex << noshowbase << uppercase << (int) str[pos];
string newvalue = oss.str();
str.replace(pos, 1, newvalue);
pos += newvalue.size();
}
str = "file:///" + str;
cout << str;
return 0;
}
Live demo
So i'm trying to make a program for c++ that will split up text by spaces and I keep getting the error Access violation writing location 0x0120FA68. Here's the code:
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <list>
#include <vector>
int main(int argc, char* argv[])
{
std::vector<char*> testVector;
char* string1 = "test f";
char seperators[] = " ";
char* token1;
char *next_token1;
int counter = 0;
token1 = strtok_s(string1, seperators, &next_token1);
while (token1 != NULL)
{
if (token1 != NULL)
{
std::cout << "\n" << token1 << std::endl;
testVector.push_back(token1);
token1 = strtok_s(NULL, seperators, &next_token1);
counter++;
}
}
std::cout << testVector.at(0);
system("pause");
return 0;
}
The strtok() family of functions modify their input strings. You are calling it on a string literal, which some compilers store in memory that is not user writeable. You can fix this by using strcpy() to copy the string literal into a buffer that you are then free to modify.