I have a QT Project where I get the full name as a QString variable fullName from user input. I'd like to store the first name (firstName) and last name (surname) in their own QString variables by extracting them from fullName .
The user input could end up adding their middle names as well so I need to to work for all kind of examples like that, eg. user input: Barry Michael Doyle would have to give firstName the value of Barry and surname the value of Doyle.
I'm not very good at QString Manipulation as I've only recently started using the Qt Library. I'd appreciate all the help I could get.
Qt's documentation on QString is pretty thorough and has a lot of examples on how to use it. You can find it here:
http://doc.qt.io/qt-5/qstring.html
In general, parsing an input string that could have mistakes in it is difficult (what would the expected behavior of an input string of "BarryDoyle" be? What about "Barrydoy le"?)
For the simple case of splitting a string using the space character you can take a look at QString::split (http://doc.qt.io/qt-5/qstring.html#split)
QString str = "Barry Michael Boyle"
QStringList list_str = str.split(" ");
QString first = list_str.first();
QString last = list_str.back();
Related
I know tupules can't be edited but I'm planning on creating a new one. I'm importing information from a file and then cutting out the first name, last name, and year of birth. I just don't know how to edit it so I can cut out everything past the comma to get each element. Sorry if this is confusing!
Here's my code!
#Open file for employee information
employee_info_file=open('employees.txt','r')
#Loop for all employees
for line in employee_info_file:
#Read info and convert to tupule
employee_info=employee_info_file.readline()
employee_tupule=(employee_info)
#Designate first name, last name, and year born
first_name=
last_name=
year_born=
employee_tupule prints like this
Mark,Acrobello,8/12/1988
But each line has a different length for first name, last name, and DOB. lease help! thanks!
I hope I understood you correctly..
you are reading a file and in each line, there is an employee with some data in this format: "Mark,Acrobello,8/12/1988" and you want to have a tuple that has 3 elements, name, last name, and the date.
you can achieve that by using the split method on the string:
employee_tuple = tuple("Mark,Acrobello,8/12/1988".split(","))
print(employee_tople)
prints:
('Mark', 'Acrobello', '8/12/1988')
Hi friends I m trying to obtain the splitted first name and last name obtained from the full name entered by user in my jsp form. After receiving the full name on submitting the form , I am splitting the fullname into two strings which is splitted with whitespaces delimiters. Here's the code to explain my problem .Please help
String name = request.getParameter("name");
String userType = request.getParameter("usertype");
//split the name into first_name and last_name
String splittedName[] = StringUtils.split(name);
System.out.println(Arrays.toString(splittedName));
String firstname = splittedName[0];
String surname = splittedName[1];
on debugging the application with breakpoints at the all the lines . I get error when i try to get splittedName[0] and splittedName[1] values into 'firstname' and 'surname' string. Please help ...sorry for any silly mistakes in my question.
String name = "Kamlesh Sharma";
String splittedName[] = name.split(" ");
System.out.println(Arrays.toString(splittedName));
String firstName = splittedName[0];
String lastName = splittedName[1];
This will serve your purpose.
Note:
You need to provide delimiter in split method and not a name which you're passing
I am developing an application using Qt/KDE. While writing code for this, I need to read a QString that contains values like ( ; delimited)
<http://example.com/example.ext.torrent>; rel=describedby; type="application/x-bittorrent"; name="differentname.ext"
I need to read every attribute like rel, type and name into a different QString. The apporach I have taken so far is something like this
if (line.contains("describedby")) {
m_reltype = "describedby" ;
}
if (line.contains("duplicate")) {
m_reltype = "duplicate";
}
That is if I need to be bothered only by the presence of an attribute (and not its value) I am manually looking for the text and setting if the attribute is present. This approach however fails for attributes like "type" and name whose actual values need to be stored in a QString. Although I know this can be done by splitting the entire string at the delimiter ; and then searching for the attribute or its value, I wanted to know is there a cleaner and a more efficient way of doing it.
As I understand, the data is not always an URL.
So,
1: Split the string
2: For each substring, separate the identifier from the value:
id = str.mid(0,str.indexOf("="));
value = str.mid(str.indexOf("=")+1);
You can also use a RegExp:
regexp = "^([a-z]+)\s*=\s*(.*)$";
id = \1 of the regexp;
value = \2 of the regexp;
I need to read every attribute like rel, type and name into a different QString.
Is there a gurantee that this string will always be a URL?
I wanted to know is there a cleaner and a more efficient way of doing it.
Don't reinvent the wheel! You can use QURL::queryItems which would parse these query variables and return a map of name-value pairs.
However, make sure that your string is a well-formed URL (so that QURL does not reject it).
I want to parse strings that consist of a 4-digit year and the week number within the year. I've followed the boost date/time IO tutorial, producing a test example like this:
std::string week_format = "%Y-W%W";
boost::date_time::date_input_facet<boost::gregorian::date, char> week_facet = boost::date_time::date_input_facet<boost::gregorian::date, char>(week_format);
std::stringstream input_ss;
input_ss.imbue(locale(input_ss.getloc(), &week_facet));
std::string input_week = "2004-W34";
input_ss.str(input_week);
boost::gregorian::date input_date;
input_ss >> input_date;
Unfortunately, input_date just prints as "2004-01-01", implying that it just parsed the year. What am I doing wrong? Is %W not available on input? (The documentation doesn't mark it as such.)
You are correct that the documentation doesn't mark it as such in the "Format Flags" section (no "!" next to it...)
http://www.boost.org/doc/libs/1_35_0/doc/html/date_time/date_time_io.html#date_time.format_flags
But that seems to be an oversight. Because in Boost's format_date_parser.hpp there is no coverage for this case in parse_date...you can look at the switch statement and see that:
http://svn.boost.org/svn/boost/trunk/boost/date_time/format_date_parser.hpp
Despite the absence of any code to do it, even the comments in the source say it handles %W and %U on parse input. What's up with that? :-/
On another note, I believe week_facet needs to be dynamically allocated in your example:
std::string week_format = "%Y-W%W";
boost::date_time::date_input_facet<boost::gregorian::date, char>* week_facet =
new boost::date_time::date_input_facet<boost::gregorian::date, char>(
week_format
);
std::stringstream input_ss;
input_ss.imbue(std::locale(input_ss.getloc(), week_facet));
(Or at least I had to do it that way to keep the example from crashing.)
Currently I am working very basic game using the C++ environment. The game used to be a school project but now that I am done with that programming class, I wanted to expand my skills and put some more flourish on this old assignment.
I have already made a lot of changes that I am pleased with. I have centralized all the data into folder hierarchies and I have gotten the code to read those locations.
However my problem stems from a very fundamental flaw that has been stumping me.
In order to access the image data that I am using I have used the code:
string imageLocation = "..\\DATA\\Images\\";
string bowImage = imageLocation + "bow.png";
The problem is that when the player picks up an item on the gameboard my code is supposed to use the code:
hud.addLine("You picked up a " + (*itt)->name() + "!");
to print to the command line, "You picked up a Bow!". But instead it shows "You picked up a ..\DATA\Images\!".
Before I centralized my data I used to use:
name_(item_name.substr(0, item_name.find('.')))
in my Item class constructor to chop the item name to just something like bow or candle. After I changed how my data was structured I realized that I would have to change how I chop the name down to the same simple 'bow' or 'candle'.
I have changed the above code to reflect my changes in data structure to be:
name_(item_name.substr(item_name.find("..\\DATA\\Images\\"), item_name.find(".png")))
but unfortunately as I alluded to earlier this change of code is not working as well as I planned it to be.
So now that I have given that real long winded introduction to what my problem is, here is my question.
How do you extract the middle of a string between two sections that you do not want? Also that middle part that is your target is of an unknown length.
Thank you so very much for any help you guys can give. If you need anymore information please ask; I will be more than happy to upload part or even my entire code for more help. Again thank you very much.
In all honeasty, you're probably approaching this from the wrong end.
Your item class should have a string "bow", in a private member. The function Item::GetFilePath would then (at runtime) do "..\DATA\Images\" + this->name + ".png".
The fundamental property of the "bow" item object isn't the filename bow.png, but the fact that it's a "bow". The filename is just a derived proerty.
Assuming I understand you correctly, the short version of your question is: how do I split a string containing a file path so I have removed the path and the extension, leaving just the "title"?
You need the find_last_of method. This gets rid of the path:
std::size_type lastSlash = filePath.find_last_of('\\');
if (lastSlash == std::string::npos)
fileName = filePath;
else
fileName = filePath.substr(lastSlash + 1);
Note that you might want to define a constant as \\ in case you need to change it for other platforms. Not all OS file systems use \\ to separate path segments.
Also note that you also need to use find_last_of for the extension dot as well, because filenames in general can contain dots, throughout their paths. Only the very last one indicates the start of the extension:
std::size_type lastDot = fileName.find_last_of('.');
if (lastDot == std::string::npos)
{
title = fileName;
}
else
{
title = fileName.substr(0, lastDot);
extension = fileName.substr(lastDot + 1);
}
See http://msdn.microsoft.com/en-us/library/3y5atza0(VS.80).aspx
using boost filesystem:
#include "boost/filesystem.hpp"
namespace fs = boost::filesystem;
void some_function(void)
{
string imageLocation = "..\\DATA\\Images\\";
string bowImage = imageLocation + "bow.png";
fs::path image_path( bowImage );
hud.addLine("You picked up a " + image_path.filename() + "!"); //prints: You picked up a bow!
So combining Paul's and my thoughts, try something like this (broken down for readability):
string extn = item_name.substr(item_name.find_last_of(".png"));
string path = item_name.substr(0, item_name.find("..\\DATA\\Images\\"));
name_ = item_name.substr( path.size(), item_name.size() - extn.size() );
You could simplify it a bit if you know that item name always starts with "..DATA" etc (you could store it in a constant and not need to search for it in the string)
Edit: Changed extension finding part to use find_last_of, as suggested by EarWicker, (this avoids the case where your path includes '.png' somewhere before the extension)
item_name.find("..\DATA\Images\") will return the index at which the substring "..\DATA\Images\" starts but it seems like you'd want the index where it ends, so you should add the length of "..\DATA\Images\" to the index returned by find.
Also, as hamishmcn pointed out, the second argument to substr should be the number of chars to return, which would be the index where ".png" starts minus the index where "..\DATA\Images\" ends, I think.
One thing that looks wrong is that the second parameter to substr should be the number of chars to copy, not the position.