Reversing a string with weird results - c++

I'm a novice programmer just trying out some exercise on C++. In this case the exercise was to reverse a string. However, when I tried to reverse a string, on some occasions the output had some weird characters at the back. Could anyone tell me what's wrong? I've tried looking through the code thoroughly and can't figure out what's wrong.
Example:
Input : Hello
Output: olleH0]
�k�]�y��jv�#�y�
#include <iostream>
#include <string.h>
using namespace std;
string FirstReverse(string str) {
int k,y,z;
k = strlen(str.c_str());
y = k-1;
char str2[k];
for (z = 0; z < k; z++) {
str2[z] = str.c_str()[y];
if (y==0) break;
else y--;
}
return str2;
}
int main() {
string x;
getline(cin, x);
cout << FirstReverse(x);
return 0;
}
EDIT:
Turns out I could do it without using C styled strings by simply:
int k,y,z;
k = str.length();
y = k-1;
string str2;
for (z = 0; z < k; z++) {
str2 += str[y];
y--;
}
return str2;

algorithm includes a function called reverse
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string my_string = "Hello World";
reverse(my_string.begin(), my_string.end());
cout << my_string << endl;
return 0;
}

Related

this bit of code, prints the binary backwards, and I got no clue why, is it something to do with the order? or another problem entirely?

this bit of code, prints the binary backwards, and I got no clue why I know it's a bit inefficient but I don't get why its backwards you can skip to case 1, the rest isn't a that important unless you want some extra details on it. anyways, if you have any ideas, it would be deeply appreciated
#include <iostream>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World";
int num = 8;
int numalt;
while (num >= 1){numalt = num % 2;num=num / 2;if (numalt <= 1){cout<<numalt;};}
return 0;
}
May have a look at this... you have to revert the result...
#include <iostream>
#include <vector>
//using namespace std;
int main()
{
std::vector<int> v{};
std::cout << "Hello World" << std::endl;
int num = 8;
int numalt;
while (num >= 1)
{
numalt = num % 2;
num = num / 2;
if (numalt <= 1)
{
v.insert(v.begin(), numalt);
//cout<<numalt;
}
}
for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
std::cout << *i;
std::cout << std::endl;
return 0;
}

add space after space in char array

So, i need to insert space after space in char string, for example:
we have string: hello world, and function should be return hello world
hello world something else => hello world something else
hello world => hello world (4 spaces) (not necessarily, but preferably)
how?? (definitely need to be used char string)
my solution (it does not work correctly because it insert only 1 space)
from hello world something it returns hello world something:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
char* addSpaces(char* str) {
char* p = strchr(str, ' ');
if (p) {
p++;
int n = strlen(p);
p[n + 1] = 0;
while (n) {
p[n] = p[n - 1];
n--;
}
*p = ' ';
}
return str;
}
int main(void) {
const int stringCount = 1;
const int c = 500;
char cstring[stringCount][c];
string str[stringCount];
for (int i = 0; i < stringCount; i++) {
cout << "Enter " << i + 1 << ". line: ";
cin.getline(cstring[i], c);
str[i] = cstring[i];
}
for (int i = 0; i < stringCount; i++) {
cout << "First function result with char in parameter: ";
char* result = addSpaces(cstring[i]);
cout << result << endl;
}
}
Using Dynamic Array:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
char *add(char *arr, int lastIndex, char key)
{
int len = sizeof(&arr);
if (len == 0 || arr[len - 1] != '\0')
{
char newArr[len + 100];
newArr[len + 100 - 1] = '\0';
strncpy(newArr, arr, len);
*arr = *newArr;
}
arr[lastIndex] = key;
return arr;
}
int main(void)
{
std::string line;
const int stringCount = 1;
const int c = 500;
cout << "Enter line: ";
std::getline(std::cin, line);
int spaceCount = 0;
char cstring[0];
int lastUpdated = 0;
for (int i = 0; i < sizeof(line); i++)
{
add(cstring, lastUpdated++, line[i]);
if (line[i] == ' ')
{
add(cstring, lastUpdated++, ' ');
}
}
cout << cstring << endl;
}
OR
Check for space first and start char str with len+spaces. and add extra space on each iterate. Else error out of index bound can come.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(void)
{
std::string line;
const int stringCount = 1;
const int c = 500;
cout << "Enter line: ";
std::getline(std::cin, line);
cout << line << endl;
int spaceCount = 0;
for (int i = 0; i < sizeof(line); i++)
{
if (line[i] == ' ')
{
spaceCount += 1;
}
}
char cstring[stringCount + spaceCount];
int j = 0;
for (int i = 0; i < sizeof(line); i++)
{
if (line[i] == ' ')
{
cstring[j++] = ' ';
cstring[j++] = ' ';
}
else
{
cstring[j++] = line[i];
}
}
cout << cstring << endl;
}
Modify the main() function according to your needs:
#include <iostream>
#include <cstring>
#include <cstdlib>
#define MAXLEN 500
void add_space(char* str, size_t index, size_t n) {
if (n >= MAXLEN) {
std::cerr << "Cannot further expand the array!" << std::endl;
abort();
}
for (auto i = n; i >= index; --i)
str[i] = str[i - 1];
str[index] = ' ';
}
char* double_spaces(char* str, size_t n) {
for (size_t i = 0; i < n; ++i)
if (str[i] == ' ')
add_space(str, i++, n++);
return str;
}
int main() {
char str[MAXLEN] = "hello world";
std::cout << double_spaces(str, std::strlen(str)) << std::endl;
return 0;
}
Sample Output:
For str[] = "hello world" function returns "hello world"
For str[] = "hello world something else" function returns "hello world something else"
For str[] = "hello world" function returns "hello world"
PS: Better algorithms are possible but they mostly require use of advanced data structures so sticking to the asker's demand of using simple cstrings I have provided one of the simplest and easy to understand solution.
Analysis: The insertion operation requires O(n-index) time which can be reduced by using something similar to ArrayLists.

Error Unhandled exception at 0x76C9FD62 in test.exe: Microsoft C++ exception: std::out_of_range at memory location 0x006FF870. occurred

I try to capitalize every first letter of the words in a sentence.
Can someone explain me why I get some error after inputting word with space ex(asdasd asdasd).
#include <iostream>
#include <cstring>
#include <vector>
#include <sstream>
#include <string>
using namespace std;
int main()
{
char str[50];
char firstLetter;
int iASCII;
vector<string> vecString;
cin.getline(str, 100);
stringstream ss(str);
string sIndivWords;
char cSpace = ' ';
while (getline(ss, sIndivWords, cSpace))
{
vecString.push_back(sIndivWords);
}
iASCII = vecString[0].at(0);
if (iASCII >= 97 && iASCII <= 122)
{
for (int i = 0; i < vecString.size(); i++)
{
firstLetter = vecString[i].at(0);
putchar(toupper(firstLetter));
for (int j = 1; j < 20;j++)
{
cout << vecString[i].at(j);
}
}
}
}
As others have stated in their comments, your (non-)magic number of 20 is the problem, here:
for (int j = 1; j < 20;j++) {
cout << vecString[i].at(j);
}
This will crash when vecString[i] has less than 20 characters!
Try using something more appropriate, like:
for (int j = 1; j < vecString[i].length(); j++) {
cout << vecString[i].at(j);
}
As a side note, your attempt to use vecString.size() will fail, because that gives you the number of separate strings, not the length of any one string.

C++ compression method for txt file

I need to create a function that counts chars in a string in C++, for example, when reading in from a text file that contains:
"aaabbbbbggssj"
the output should be:
"3a5b2g1j"
Im really not sure how to go about it and any help would be greatly appreciated! Thanks
My code is as follows:
#include <iostream>
using namespace std;
#include "Character.h"
#include <fstream>
#include <string>
using namespace std;
int main(){
int c;
void count(char [], int []);
//opening text file
string line = " ";
fstream my_stream;
my_stream.open("information.txt");
//loop to cout occurences of each character
while (getline (my_stream,line))
{
cout << line << '\n';
c += line.length();
cout << c;
int numOfChars = line.length();
for (unsigned int i = 0; i < line.length(); i++){
}
my_stream.close();
return 0;
}
Just count repeating symbols and produce result:
string compress(string const& str) {
string result = "";
int i = 0;
while (str[i]) {
int c = 1;
while (str[i] == str[i + c]) ++c;
result += std::to_string(c) + str[i];
i += c;
}
return result;
}

Counting the number of occurrences of a string within a string

What's the best way of counting all the occurrences of a substring inside a string?
Example: counting the occurrences of Foo inside FooBarFooBarFoo
One way to do is to use std::string find function:
#include <string>
#include <iostream>
int main()
{
int occurrences = 0;
std::string::size_type pos = 0;
std::string s = "FooBarFooBarFoo";
std::string target = "Foo";
while ((pos = s.find(target, pos )) != std::string::npos) {
++ occurrences;
pos += target.length();
}
std::cout << occurrences << std::endl;
}
#include <iostream>
#include <string>
// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
if (sub.length() == 0) return 0;
int count = 0;
for (size_t offset = str.find(sub); offset != std::string::npos;
offset = str.find(sub, offset + sub.length()))
{
++count;
}
return count;
}
int main()
{
std::cout << countSubstring("FooBarFooBarFoo", "Foo") << '\n';
return 0;
}
You should use KMP Algorithm for this.
It solves it in O(M+N) time where M and N are the lengths of the two strings.
For more info-
https://www.geeksforgeeks.org/frequency-substring-string/
So what KMP Algorithm does is, it search for string pattern. When a pattern has a sub-pattern appears more than one in the sub-pattern, it uses that property to improve the time complexity, also for in the worst case.
The time complexity of KMP is O(n).
Check this out for detailed algorithm:
https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
#include <iostream>
#include<string>
using namespace std;
int frequency_Substr(string str,string substr)
{
int count=0;
for (int i = 0; i <str.size()-1; i++)
{
int m = 0;
int n = i;
for (int j = 0; j < substr.size(); j++)
{
if (str[n] == substr[j])
{
m++;
}
n++;
}
if (m == substr.size())
{
count++;
}
}
cout << "total number of time substring occur in string is " << count << endl;
return count;
}
int main()
{
string x, y;
cout << "enter string" << endl;
cin >> x;
cout << "enter substring" << endl;
cin >> y;
frequency_Substr(x, y);
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1,s2;
int i=0;
cout<<"enter the string"<<endl;
getline(cin,s1);
cout<<"enter the substring"<<endl;
cin>>s2;
int count=0;
string::iterator it=s1.begin();
while(it!=s1.end())
{
if(*it==s2[0])
{
int x =s1.find(s2);
string subs=s1.substr(x,s2.size());
if(s2==subs)
count++;
}
++it;
}
cout<<count<<endl;
return 0;
}