How to remove the first two characters of a QString - c++

How would I remove the the first two characters of a QString or if I have to put it a StackOverflows layman's terms:
QString str = "##Name" //output: ##Name
to
output: Name
So far I have used this small piece of code:
if(str.contains("##"))
{
str.replace("##","");
}
..but it doesn't work as I would need to have "##" in some other strings, but not at the beginning.
The first two characters may occur to be "%$" and "##" as well and that mostly the reason why I need to delete the first two characters.
Any ideas?

This the syntax to remove the two first characters.
str.remove(0, 2);

You can use the QString::mid function for this:
QString trimmed = str.mid(2);
But if you wish to modify the string in place, you would be better off using QString::remove as others have suggested.

You can use remove(const QRegExp &rx)
Removes every occurrence of the regular expression rx in the string, and returns a reference to the string. For example:
QString str = "##Name" //output: ##Name
str.remove(QRegExp("[#]."));
//strr == "Name"

Related

Replace single backslash with double in a string c++

I am trying to replace one backslash with two. To do that I tried using the following code
str = "d:\test\text.txt"
str.replace("\\","\\\\");
The code does not work. Whole idea is to pass str to deletefile function, which requires double blackslash.
since c++11, you may try using regex
#include <regex>
#include <iostream>
int main() {
auto s = std::string(R"(\tmp\)");
s = std::regex_replace(s, std::regex(R"(\\)"), R"(\\)");
std::cout << s << std::endl;
}
A bit overkill, but does the trick is you want a "quick" sollution
There are two errors in your code.
First line: you forgot to double the \ in the literal string.
It happens that \t is a valid escape representing the tab character, so you get no compiler error, but your string doesn't contain what you expect.
Second line: according to the reference of string::replace,
you can replace a substring by another substring based on the substring position.
However, there is no version that makes a substitution, i.e. replace all occurences of a given substring by another one.
This doesn't exist in the standard library. It exists for example in the boost library, see boost string algorithms. The algorithm you are looking for is called replace_all.

Quotation mark in return C++

I get a code like this
virtual Qstring getEnergies() const {
return "estrain"
",eslip"
",edashpot";
}
Could you guys please explain the meaning of quotation and comma marks in that code? I am really thankful
Adjacent string literals are concatenated in C++. So
"foo" "bar"
Becomes
"foobar"
In your case the function will return a Qstring with the value of
"estrain,eslip,edashpot"
This behavior is defined in section 2.2.6 [lex.phases] of the C++ standard
Adjacent string literal tokens are concatenated.
The commas are a red herring; this is just concatenation of string literals.
In source code, "abc" "def" means the same thing as "abcdef".
The quotation mark here is because your function return type is string. So "" is for the string type return.
Now the second part as to why you have comma, then as others have answered it is for getting the adjacent string literal or different string literals. If you remove the comma then you will get a single string. If you don't have the comma then the return string will be equivalent to estraineslipedashpot

capture IP addresses only using R

I have R objects that have domain names and IP addresses in them. For example.
11.22.44.55.test.url.com.localhost
I used regex in R to capture the IP addresses. My problem is that when there is no match the whole string gets matched or "outputed". This becomes a problem as I work on a very large dataset. I currently have the following using regex
sub("([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+).*","\\1.\\2.\\3.\\4","11.22.44.55.test.url.com.localhost")
which gives me 11.22.44.55
11.22.44.55
but if I were to have to following
sub("([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+).*","\\1.\\2.\\3.\\4","11.22.44.test.url.com.localhost")
Then it gives me
11.22.44.test.url.com.localhost
which is actually not correct. Wondering if there is any solution for this.
You could pre-process with grep to get only the strings that are formatted they way you want them, then use gsub on those.
x <- c("11.22.44.55.test.url.com.localhost", "11.22.44.test.url.com.localhost")
gsub("((\\d+\\.){3}\\d+)(.*)", "\\1", grep("(\\d+\\.){4}", x, value=TRUE))
#[1] "11.22.44.55"
Indeed, your code is working. When sub() fails to match, it returns the original string. From the manual:
For sub and gsub return a character vector of the same length and with the same attributes as x (after possible coercion to character). Elements of character vectors x which are not substituted will be returned unchanged (including any declared encoding). If useBytes = FALSE a non-ASCII substituted result will often be in UTF-8 with a marked encoding (e.g. if there is a UTF-8 input, and in a multibyte locale unless fixed = TRUE). Such strings can be re-encoded by enc2native.
Emphasis added
You could try this pattern:
(?:\d{1,3}+\.){3}+\d{1,3}
I have tested it in Java:
static final Pattern p = Pattern.compile("(?:\\d{1,3}+\\.){3}+\\d{1,3}");
public static void main(String[] args) {
final String s1 = "11.22.44.55.test.url.com.localhost";
final String s2 = "11.24.55.test.url.com.localhost";
System.out.println(getIps(s1));
System.out.println(getIps(s2));
}
public static List<String> getIps(final String string) {
final Matcher m = p.matcher(string);
final List<String> strings = new ArrayList<>();
while (m.find()) {
strings.add(m.group());
}
return strings;
}
Output:
[11.22.44.55]
[]
Look at the gsubfn or strapply functions in the gsubfn package. When you want to return the match rather than replace it, these functions work better than sub.

Regular Expression for removing suffix

What is the regular expression for removing the suffix of file names? For example, if I have a file name in a string such as "vnb.txt", what is the regular expression to remove ".txt"?
Thanks.
Do you really need a regular expression to do this? Why not just look for the last period in the string, and trim the string up to that point? Frankly, there's a lot of overhead for a regular expression, and I don't think you need it in this case.
As suggested by tstenner, you can try one of the following, depending on what kinds of strings you're using:
std::strrchr
std::string::find_last_of
First example:
char* str = "Directory/file.txt";
size_t index;
char* pStr = strrchr(str,'.');
if(nullptr != pStr)
{
index = pStr - str;
}
Second example:
int index = string("Directory/file.txt").find_last_of('.');
If you are using Qt already, you could use QFileInfo, and use the baseName() function to get just the name (if one exists), or the suffix() function to get the extension (if one exists).
If you're looking for a solution that will give you anything except for the suffix, you should use string::find_last_of.
Your code could look like this:
const std::string removesuffix(const std::string& s) {
size_t suffixbegin = s.find_last_of('.');
//This will handle cases like "directory.foo/bar"
size_t dir = s.find_last_of('/');
if(dir != std::string::npos && dir > suffixbegin) return s;
if(suffixbegin == std::string::npos) return s;
else return s.substr(0,suffixbegin);
}
If you're looking for a regular expression, use \.[^.]+$.
You have to escape the first ., otherwise it will match any character, and put a $ at the end, so it will only match at the end of a string.
Different operating systems may allow different characters in filenams, the simplest regex might be (.+)\.txt$. Get the first capture group to get the filename sans extension.

How to use string and string pointers in C++

I am very confused about when to use string (char) and when to use string pointers (char pointers) in C++. Here are two questions I'm having.
which one of the following two is correct?
string subString;
subString = anotherString.sub(9);
string *subString;
subString = &anotherString.sub(9);
which one of the following two is correct?
char doubleQuote = aString[9];
if (doubleQuote == "\"") {...}
char *doubleQuote = &aString[9];
if (doubleQuote == "\"") {...}
None of them are correct.
The member function sub does not exist for string, unless you are using another string class that is not std::string.
The second one of the first question subString = &anotherString.sub(9); is not safe, as you're storing the address of a temporary. It is also wrong as anotherString is a pointer to a string object. To call the sub member function, you need to write anotherString->sub(9). And again, member function sub does not exist.
The first one of the second question is more correct than the second one; all you need to do is replace "\"" with '\"'.
The second one of the second question is wrong, as:
doubleQuote does not refer to the 10th character, but the string from the 10th character onwards
doubleQuote == "\"" may be type-wise correct, but it doesn't compare equality of the two strings; it checks if they are pointing to the same thing. If you want to check the equality of the two strings, use strcmp.
In C++, you can (and should) always use std::string (while remembering that string literals actually are zero-terminated character arrays). Use char* only when you need to interface with C code.
C-style strings need error-prone manual memory management, need to explicitly copy strings (copying pointers doesn't copy the string), and you need to pay attention to details like allocating enough memory to have the terminating '\0' fit in, while std::string takes care of all this automagically.
For the first question, the first sample, assuming sub will return a substring of the provided string.
For the second, none:
char doubleQuote = aString[9];
if( doubleQuote == '\"') { ... }
Erm, are you using string from STL?
(i.e. you have something like
#include <string>
#using namespace std;
in the beginning of your source file ;) )
then it would be like
string mystring("whatever:\"\""");
char anElem = mystring[9];
if (anElem=="\"") { do_something();}
or you can write
mystring.at(9)
instead of square brackets.
May be these examples can help.