How to get multiple characters from a string - c++

I am currently trying to learn c++, and I was informed that this website is a great place to start getting involved in.
I was just wondering if it were possible to retrieve multiple characters from a string rather then repeating multiple lines of code.
string lname = "";
char l = lname.at(0);
char a = lname.at(1);

A string is essentially a char array followed by a NULL character.
The string class reference guide will help you know what you can and cannot do with a string variable. You didn't provide enough details for us to thoroughly answer your question, but if you are looking for a substring, try using the ".substr" function in the string class.
For instance:
string tempString = "Hello, my name is brw59";
// at character 7 (starts at 0) print two characters
cout << tempString.substr(7, 2); // output == "my"

Related

String handling with Nordic characters is difficult in C++

I have tried many ways to solve this problem. I just want to part a string or do stuff with each character. As soon as there are Nordic characters in the string, it's not possible to part that string.
The length() function returns the right answer if we look at memory use, but that's not the same as the string length. "ABCÆØÅ" does not have 6 as the length, is has 9. One extra for each special character.
Anybody with a good answer??
The test under here, shows the problem, some letters and a lot of ? marks. :-(
int main()
{
string name = "some æøå string";
for_each(name.begin(), name.end(), [] (char c) {
cout << c;
cout << endl;
});
}
If your terminal supports utf-8 encoding shouldn't be no problem in using the std::cout with the string you enter, but, you need to tell the compiler that you typed in an utf8 string, like this:
int main()
{
string name = u8"some æøå string";
for_each(name.begin(), name.end(), [] (char c) {
cout << c;
cout << endl;
});
cout<<name; //this will also work
return 0; //add this just to be tidy
}
you need to that because characters in UTF-8 might need 1,2,3 or 4 bytes depending on its face.
Then depending on what you need to do, for example split between characters, you should create a function to detect how long is each utf8 character. Then you create a 'string' for each utf8 character and extract as many characters as needed from the original string.
There is a very good library (very compact) utf8proc that let you do those such things.
utf8proc helped me in many projects for resolving these kind of issues.

Split string by delimiter strtok weird behaviour

I am trying to split string ,but unfortunately strtok behaves weirdly
I have following string get|user=password|23|info|hello I have tried widely used method using strtok, but unfortunately it treats = as delimiter and I cannot parse my string.
So get parsed correctly than parsed only user, but not user=password.
Please help to find the problem or suggest any other way to split the string.
I am programming for Arduino.
Thanks
Code
const char delimeter = '|';
char *token;
token = strtok(requestString, &delimeter);
// Handle parsed
token = strtok(NULL, &delimeter);
From cppreference,
delim - pointer to the null-terminated byte string identifying delimiters
The requirement that your approach doesn't fit is null terminated. You take the address of a single char, but clearly you cannot access anything past this one symbol. strtok, however, searches for \0 character which terminates the string. Thus you're entering undefined behaviour land.
Instead, use
const char* delimiter = "|";
Change this:
const char delimeter = '|';
to this:
const char * delimeter = "|"; // note the double quotes

How to assign string a char array that starts from the middle of the array?

For example in the following code:
char name[20] = "James Johnson";
And I want to assign all the character starting after the white space to the end of the char array, so basically the string is like the following: (not initialize it but just show the idea)
string s = "Johnson";
Therefore, essentially, the string will only accept the last name. How can I do this?
i think you want like this..
string s="";
for(int i=strlen(name)-1;i>=0;i--)
{
if(name[i]==' ')break;
else s+=name[i];
}
reverse(s.begin(),s.end());
Need to
include<algorithm>
There's always more than one way to do it - it depends on exactly what you're asking.
You could either:
search for the position of the first space, and then point a char* at one-past-that position (look up strchr in <cstring>)
split the string into a list of sub-strings, where your split character is a space (look up strtok or boost split)
std::string has a whole arsenal of functions for string manipulation, and I recommend you use those.
You can find the first whitespace character using std::string::find_first_of, and split the string from there:
char name[20] = "James Johnson";
// Convert whole name to string
std::string wholeName(name);
// Create a new string from the whole name starting from one character past the first whitespace
std::string lastName(wholeName, wholeName.find_first_of(' ') + 1);
std::cout << lastName << std::endl;
If you're worried about multiple names, you can also use std::string::find_last_of
If you're worried about the names not being separated by a space, you could use std::string::find_first_not_of and search for letters of the alphabet. The example given in the link is:
std::string str ("look for non-alphabetic characters...");
std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
if (found!=std::string::npos)
{
std::cout << "The first non-alphabetic character is " << str[found];
std::cout << " at position " << found << '\n';
}

Understanding a C++ program [ Bjarne Stroustrup's book ]

i need your precious help for a small question!
I'm reading the Bjarne Stroustrup's book and i found this exemple:
int main()
{
string previous = " ";
string current;
while (cin >> current) {
if(previous == current)
cout << "repeated word: " << current << '\n';
previous = current;
}
return 0;
}
My question is: What does string previous = " "; do?
It initializes previous to the character space (like when you press space). But I thought in C++ it doesn't read it, something about the compiler skipping over whitespace. Why initialize it to that then?
I have tried to write like that: string previous; and the program still work properly... so? What is the differnece? Please enlighten me x)
You seam to be confused on what it means in C++ to ignore whitespace. In C++
std::string the_string = something;
is treated the same as
std::string the_string=something ;
No when you have a string literal the whitespace in the literal is not ignored as it is part of the charcters of the string. So
std::string foo = " ";
Creates a string with one space where as
std::string foo = " ";
Creates a string with 4 spaces in it.
You are right, a whitespace is something you will never get when reading input using std::cin. Therefore, a previous string is initialized with a value that could never (i.e. when reading the first word) possibly match word read into current string.
In this case previous could alsobe initalized to an empty string, because istream::operator>> skips all the whitespace and you would never get an empty like by reading from std::cin that way. However, there are other ways of using std::cin (e.g. together with getline()), which may lead to reading an empty string.
The book explains this example in every detail.
string previous = " ";
assigns a space to the string variable 'previous'.
It may still 'work', but if you were to simply press enter on the first try, the 'repeated word' message should appear.
He could just write :)
string previous;
The idea is that the operator >> can not enter an empty string if by default there is set to skip white spaces.
So any comparison current with an empty string or a string that contains white spaces will yield false.

sscanf for this type of string

I'm not quite sure even after reading the documentation how to do this with sscanf.
Here is what I want to do:
given a string of text:
Read up to the first 64 chars or until space is reached
Then there will be a space, an = and then another space.
Following that I want to extract another string either until the end of the string or if 8192 chars are reached. I would also like it to change any occurrences in the second string of "\n" to the actual newline character.
I have: "%64s = %8192s" but I do not think this is correct.
Thanks
Ex:
element.name = hello\nworld
Would have string 1 with element.name and string2 as
hello
world
I do recommend std::regex for this, but apart from that, you should be fine with a little error checking:
#include <cstdio>
int main(int argc, const char *argv[])
{
char s1[65];
char s2[8193];
if (2!=std::scanf("%64s = %8192s", s1, s2))
puts("oops");
else
std::printf("s1 = '%s', s2 = '%s'\n", s1, s2);
return 0;
}
Your format string looks right to me; however, sscanf will not change occurences of "\n" to anything else. To do that you would then need to write a loop that uses strtok or even just a simple for loop evaluating each character in the string and swapping it for whatever character you prefer. You will also need to evaluate the sscanf return value to determine if the 2 strings were indeed scanned correctly. sscanf returns the number of field successfully scanned according to your format string.
#sehe shows the correct usage of sscanf including the check for the proper return value.