Finding the last index of the first substring found in a string - c++

I was looking through a lot of the solutions on here and there doesn't seem to be anything that does this with a built-in c++ method.
std::string str = "Hey I'm John, John's friend";
int substrindex = str.find("John"); // Finds the index of "J" from the first "John"
// But what If I wanted to find the end of the substring of str "n" using a built-in method like find?

If you mean that you want the last index for a specific word in a givin string, then you can do it like this
std::string str = "Hey I'm John,John's
friend";
std:: string word="John";
int index=str.find(word)+word.size()-1;
std::cout<<index;
if you mean something else, you should clarify more.

Related

How can i find the index of the first alphabet of second last word in a string [duplicate]

This question already has answers here:
Kotlin function for getting start and end index of substring
(2 answers)
Closed 1 year ago.
I want to find index from string. How can i find the index of the first alphabet of second last word in a string.
val index = "Hey! How are you men? How you doing"
i want to search you doing from the above string, but i want y index from the word you. I did some code to find index but I am unable to find it.
fun main(vararg args: String) {
val inputString = "Hey! How are you men? How you doing"
val regex = "you doing".toRegex()
val match = regex.find(inputString)!!
println(match.value)
println(match.range)
}
This regex finds the last two words in your sentence and calculates the index by subtracting the length of the two words from the length of the string.
val result = Regex("^(?:.*?\\s+)?([^\\s]+\\s+[^\\s]+)$").matchEntire(inputString)
if (result != null) {
println(inputString.length - result.groupValues[1].length)
} else {
println("not supported")
}
Supports inputs like
Hey! How are you men? How you doing
Hey! How are you men? How you doing?
Hey! How are you, John?
Hello there!
Split the string, then take the first character of the second-to-last element of the resulting array.
If you are looking for the index of the y in you doing related to the entire string (Hey! How are you men? How you doing), you can use indexOf.
val inputString = "Hey! How are you men? How you doing"
val matchString = "you doing"
val matchIndex = inputString.indexOf(matchString)
More info on indexOf here.
If you don't want to use a regex (which you probably shouldn't unless you need the efficiency) the simplest option is probably what #samuei says:
index.split(' ').takeLast(2).first().first()
(take the last two words, take the first of those, and then the first character of that)
If you want to mess with indices instead you could do this kind of thing:
val lastSpaceIndex = index.lastIndexOf(' ')
val secondToLastSpace = index.lastIndexOf(' ', startIndex = lastSpaceIndex -1)
println(index.get(secondToLastSpace + 1))
where you're finding the index of the last space, then the index of the last space before that one, and then grabbing the character after that. But this is already getting a lot less readable, and is it worth the extra complexity? Your call!

C++ Substract the end of a string, not knowing length of the result

I have a string like this: 001,"John Marvin","doctor", "full time"
I want to delete everything after (001) with substr, but, the length of (001) is not always 3 so I can not put something like thie:
string chain = "001,\"John Marvin\",\"doctor\", \"full time\"";
std::string partial = chain.substr(0,3);
How can I proceed in this case?
You could find the index of the first comma and use that to determine where to cut off the string.
Something like:
string chain = "001,\"John Marvin\",\"doctor\", \"full time\"";
int cutoff = chain.find(',');
string newString = chain.substr(0, cutoff);
Tested here.

Find a special part in a string

I try to locate a special part in a string.
The example of string as follow:
22.21594087,1.688530832,0
I want to locate 1.688530832 out.
I tried
temp.substr(temp.find(",")+1,temp.rfind(","));
and got 1.688530832,0.
I replaced rfind() with find_last_of() but still got the same result.
temp.substr(temp.find(",")+1,temp.find_last_of(","));
I know this is a simple problem and there are other solutions.But I just want to know why the rfind did not work.
Thank you very much!
The second argument for substr is not the ending index, but rather the length of the substring you want. Simply throw in the length of 1.688530832 and you'll be fine.
If the length of the search string is not available, then you can find the position of the last comma and subtract that from the position of the first character of the special word:
auto beginning_index = temp.find(",") + 1;
auto last_comma_index = temp.rfind(",");
temp.substr(beginning_index, last_comma_index - beginning_index);
I see what you are doing. You are trying to have kind of iterators to the beginning and the end of a substring. Unfortunately, substr does not work that way, and instead expects an index and an offset from that index to select the substring.
What you were trying to achieve can be done with std::find, which does work with iterators:
auto a = std::next(std::find(begin(temp), end(temp), ','));
auto b = std::next(std::find(rbegin(temp), rend(temp), ',')).base();
std::cout << std::string(a, b);
Live demo

Spliting string into a list of substrings

I have a string id <- "Hello these are words N12345678 hooray how fun".
I would like to extract just N12345678 from this string.
So far I have used strsplit(id, " "). Now I have
>id
>[[1]]
>[1] "Hello" "these" "are" "words" "N12345678" "hooray" "how"
>[8] "fun"
Which is of type list and of length 1 (despite apparently having 8 elements?)
If I then use id <- id[grep("^[N][0-9]",id)],
id is an empty list.
I think what I need to do is split the string into a list of length 8 with each element as a substring and then grep should be able to pick out the pattern, but I'm not sure how to go about that.
Use regmatches
> regmatches(id, regexpr("N[0-9]+", id))
[1] "N12345678"
If you insist on using strsplit. I think this can solve the problem:
id <- "Hello these are words N12345678 hooray how fun"
id = strsplit(id, " ")
id[[1]][grep("^N[1-9]", id[[1]])]
Notice that I haven't changed your regex. It could be more precise expression such as ^N\\d+$.
Do you know about strtok? It will parse your input line on certain characters. For the purpose of my example, I am breaking off a piece of my string every time I hit a space.
tempVar = strtok(string, " ");
// tempVar has "id" or everything up to the first space
while (tempVar != NULL)
{
tempVar = strtok(NULL, " ");
//now tempVar picked up the next word, and will loop picking up the next word until the end of string
}
Using this, your "Hello these are words N123456789 Hooray" would do this:
tempVar would be Hello, then "these" etc etc.
Each time through the loop tempVar would get a new value. So i would suggest evaluating tempVar in the loop (before grabbing the next one) so that you can stop when you have N123456789
Try:
gsub('\\b[a-zA-Z]+\\b','',id)

Verify and cut a string using regexp in matlab

I have the following string:
{'output',{'variable','VGRG_Pos_Var1/Parameters/D_foo'},'date',734704.60904050921}
I would like to verify the format of the string that the word 'variable' is the second word and i would like to retrive the string after the last '/' in the 3rd string (In this example 'D_foo').
how could i verify this and retrive the sting i search?
I tried the following:
regexp(str,'{''\w+'',{''variable'',''([(a-z)|(A-Z)|/|_])+')
without success
REMARK
The string to analysis is not splited after the komma, it is only due to length of the string.
EDIT
my string is:
'{''output'',{''variable'',''VGRG_Pos_Var1/Parameters/D_foo''},''date'',734704.60904050921}';
and not a cell, which could be understood. I added the sybol ' at the start and end of the string to symbolizied that it is a string.
I realise that you mention using regexp in the question, but I'm not sure if this is a requirement? If other solutions are acceptable you could try this:
str='{''output'',{''variable'',''VGRG_Pos_Var1/Parameters/D_foo''},''date'',734704.60904050921}';
parts1=textscan( str, '%s','delimiter',{',','{','}'},'MultipleDelimsAsOne',1);
parts2=textscan( parts1{1}{3}, '%s','delimiter',{'/',''''},'MultipleDelimsAsOne',1);
string=parts2{1}{end}
match=strcmp(parts1{1}{2},'variable')
To answer the first part of your question, you can write this:
str = {'output',{'variable','VGRG_Pos_Var1/Parameters/D_foo'},'date',734704.60904050921};
temp = str(2); %this holds the cell containing the two strings
if cmpstr(temp{1}(1), 'variable')
%do stuff
end
For the second part you can do this:
str = {'output',{'variable','VGRG_Pos_Var1/Parameters/D_foo'},'date',734704.60904050921};
temp = str(2); %like before, this contains the cell
temp = temp{1}(2); %this picks out the second string in the cell
temp = char(temp); %turns the item from a cell to a string
res = strsplit(temp, '/'); %splits the string where '/' are found, res is an array of strings
string = res(3); %assuming there will always be just 2 '/'s.