I have a string..."APPLES" and i'm having difficulty using substring to effectively manipulate the string. My goal is to add a '-' every 3 characters. My problem is that when "APPLES" goes through, it returns "APP-ES-" which is incorrect, I'm trying to make it return "APP-LES-" any suggestions? Here is my code thus far...
for(int j = 0; j <= str.length(); j++){
str_substr += str.substr(j,j+3);
str_substr = str_substr + '-';
j = j+3;
cout << str_substr;
}
Just build a separate string by copying the relevant parts.
std::string s;
for(size_t i = 0; i < str.length(); i += 3) {
s += str.substr(i, 3) + "-";
}
(Just so you note it for sure: str.substr(j,j+3); is incorrect, it won't copy 3 characters, it will copy j + 3 characters. Read the documentation more carefully.)
You're incrementing j twice:
for(int j = 0; j <= str.length(); j++){
^-- once here
...
j = j+3;
^-- and again here
Also, it looks like you might get two -s at the end of a string with a length that's a multiple of three, since you're checking for j <= str.length() instead of j < str.length() Try:
for(size_t j = 0; j < str.length(); j+=3){
str_substr += str.substr(j,3) + '-';
}
cout << str_substr;
Since you're apparently just copying the result to cout, anyway, perhaps it's easiest to skip the intermediate string, and just copy 3 characters to cout, then write a -, three more characters, etc.
#include <string>
#include <iterator>
#include <iostream>
int main(){
std::string input("APPLES");
size_t len = 3;
for (size_t pos = 0; pos < input.length(); pos += len)
std::cout << input.substr(pos, len) << "-";
}
If you need to modify the existing string, you probably want to start by computing the number of dashes you're going to insert, then work from the end of the string back to the beginning, moving each character directly to its destination. If you start at the front and insert dashes where needed, it ends up as an O(N2) algorithm. Working from end to beginning and moving each character directly to its destination is O(N) instead.
Related
I need to find longest common substring from two DNA strings.
I have first string "CGATAC", and second: "GACAGTC"
With my code my result is: "GAC", but you can get longer substring, i mean "GATC". What i need to change to get longer substring ?
int k = 0;
for (int i = 0; i < substring1.length(); i++) {
char znak = substring1[i];
for (int j = k; j < substring2.length(); j++) {
char znak2 = substring2[j];
if (znak == znak2) {
end_substring += znak;
k = j;
break;
}
}
}
cout << end_substring;
You can improve your code with some basic ideas. I understand you want one of the longest strings, not all, then you can store the length of the longest string until each moment in the program, and use this length for search string at least of length+1. But the bes solution is use dynamic porgramming, you can read this solution here: https://www.geeksforgeeks.org/longest-common-substring-dp-29/
I am attempting to add space before a character in a string by using the insert function.
Can someone kindly explain why the following code does not work ?
for(int i = 0; i < line.length(); i++)
{
if(line[i+1] == '=')
{
line.insert(i, " ");
}
}
If you want to insert before = you can get the index of = directly and not the index of char followed by =. This could lead to out of bounds access.
Also, when you insert the space you extend your string by 1, that's ok but only if you also adjust the counter i, otherwise it will insert again and again and again before = resulting in infinite loop. Adjust your code in this manner:
for (int i = 0; i < line.length(); i++)
{
if (line[i] == '=')
{
line.insert(i++, " ");
}
}
The code seems fine except for one little detail:
Imagine you have a string with "test=something". When you iterate it, when i is 3 you will find the next character is an equals, so you put a space into it. Next iteration i will be 4, but you just added a space, so at i equals 5 there's the same equals sign. So you put another space and so on. TO fix this youy can try:
std::string line = "test=something";
for (int i = 0; i < line.length(); i++)
{
if (line[i + 1] == '=')
{
i++;
line.insert(i, " ");
}
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word, wordbackw;
getline(cin, word);
int size = word.size();
for (int i = 0; i < size ; i++)
word[size-1-i] = wordbackw[i];
cout << wordbackw << endl;
return 0;
}
The only thing that appears in the cmd is my input.
Thanks for any help.
EDIT: Sorry, forgot to add cout to the code.
You must first resize wordbackw to the same size as word:
You could either initialize wordbackw = word; before the loop and print out the result in word.
Or you could resize wordbackw before the loop and copy word letters to wordbackw letters (you do the oposite for now), and display the result in wordbackw
Two issues:
You are overriding the input that you read with non-existent characters when you do word[size-1-i] = wordbackw[i]; try doing wordbackw.push_back(word[size-1-i]);
You are not printing anything to the standard output after reading. Do this
cout << wordbackw << endl;
You're missing any kind of code to display the reversed string. You only reversed it in memory.
Try adding something to display the text after you reverse it, such as
cout << wordbackw;
Oh, well and also your word swapping code looks backwards in a couple of ways. You load it into word but then try to set word to the reverse of wordbackw, which is empty. Also the indexing looks off - you're assigning locations in an empty string, and you're indexing forwards through the source string rather than backwards. So you'd want to do something more like:
for (int i = size - 1; i >= 0 ; i--)
wordbackw += word[i];
The object wordbackw is empty. So you may not apply the subscript operator for the object. Also you should at least exchange the operands in this statement
word[size-1-i] = wordbackw[i];
provided that the operands will be written correctly.
You could write instead of this code snippet
int size = word.size();
for (int i = 0; i < size ; i++)
word[size-1-i] = wordbackw[i];
the following
wordbackw.reserve( word.size() );
for ( auto i = word.size(); i != 0 ; i-- )
wordbackw.push_back( word[i - 1] );
Or
wordbackw.reserve( word.size() );
for ( auto i = word.size(); i != 0 ; i-- )
wordbackw += word[i - 1];
Or you could do the same without using the loop. For example
wordbackw.assign( word.rbegin(), word.rend() );
I have written this function that reverses the order of words within a string, the function behaves as expected until it has read two words then starts to behave unexpectedly:
string ReverseString(string InputString){
int EndOfGroup = 0;
string ReversedString = " ";
int k = 0;
ReversedString.resize(InputString.size());
for (int i = InputString.length(); i > 0; i--){
if (isspace(InputString[i]))
{
EndOfGroup = i;
for (int j = i; j >= EndOfGroup && j < InputString.length(); j++)
{
ReversedString[k] = InputString[j] ;
k++;
}
}
}
What I mean by behaves unexpectedly is that once I pass a string to the function it starts to populate the ReversedString variable with garbage values until the goes out of bounds.
This shoes the point the programme crashes:
InputString "the brown fox died"
ReversedString " died fox died brownÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ"
j 9
i 3
EndOfGroup 3
k 20
This is not a duplicate question as my method is different to existing methods out there.
Think about the inner loop,
for (int j = i; j >= EndOfGroup && j < InputString.length(); j++)
For the first word, this is good, now for the second word - are the conditions correct?
Remember you are writing to the reversed string using an incrementing index k...
You are copying the word only when you are meeting space sign
if (isspace(InputString[i]))
{
//start of copying...
what does mean that you will not copy the first work (there is no space before the word).
resize() method is fullfilling the string will null character (due to reference) and they are probably show as
ÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ
You need to handle the first word
for (int i = InputString.length(); i >= 0; i--){
if (isspace(InputString[i]) || i == 0)
Also it would be good to provide some default char instead of null by using
ReversedString.resize(InputString.size(), ' ');
It works with Visual Studio, but segfaults in Cygwin, which is weird because I'm compiling the same source, and both generate a Windows executable. GDB doesn't work very well for me in Cygwin for some reason, and the error doesn't appear in VS so I can't really debug it there.
Any ideas?
int main(void)
{
Pair ***occurences = new Pair**[20];
int i, j, k;
for (i = 0; i < 20; i++)
{
occurences[i] = new Pair*[i+1];
for (j = 0; j < i+1; j++)
{
occurences[i][j] = new Pair[26];
for (k = 0; k < 26; k++)
{
Pair pair;
pair.c = k + 'a';
pair.occurs = 0;
occurences[i][j][k] = pair;
}
}
}
std::fstream sin;
sin.open("dictionary.txt");
std::string word;
while (std::getline(sin, word))
{
if (word.size() < 21)
{
for (i = 0; i < word.size(); i++)
{
// SEGFAULTING HERE
occurences[word.size()-1][i][word[i] - 'a'].occurences++;
}
}
}
for (i = 0; i < 20; i++)
{
for (j = 0; j < i+1; j++)
{
delete [] occurences[i][j];
}
delete [] occurences[i];
}
delete [] occurences;
return 0;
}
You marked this line as the critical point:
occurences[word.size()-1][i][word[i] - 97].occurs++;
All three array accesses might go wrong here, and you would have to check them all:
It seems like the first dimension of the array has the length 20, so the valid values for the index are [0..19]. word.size()-1 will be less than 0 if the size of the word is zero itself, and it will be larger than 19 if the size of the word is 21 or more.
Are you sure the length of the word is always in the range [1..20]?
The second dimension has variable length, depending on the index of the first dimension. Are you sure this never gets out of bound?
The third dimension strikes me as the most obvious. You subtract 97 from the character code, and use the result as index into an array with 26 entries. This assumes that all characters are in the range of [97..122], meaning ['a'..'z']. Are you sure that there will never be other characters in the input? For example, if there are any capital characters, the resulting index will be negative.
Just reformulating my comment as an answer:
occurences[word.size()-1][i][word[i] - 'a'].occurs++;
if word.size() is 100 (for example) this will crash (for i == 0) since occurences has only 20 elements.