Find character in a string - c++

I cant get the char search to work. The substring function is working but the char search won't provide the right location of the char it is looking for
#include<iostream>
#include <string>
using namespace std;
int charsearch(string searchInto, char ch, int start = 0)
{
int x = 0;
long n = searchInto.length();
for (int i = 1; i < n; i++)
{
cout << ch;
if (searchInto[i] == ch)
{
i = x;
}
else
i++;
}
cout<< x;
return x;
}
int substr(string src, string tosearch, int start = 0)
{
string searchInto = src;
long n = searchInto.size();
long m = tosearch.size();
int ans = -1;
for (int i = start; i < n; ++i)
{
int p = i;
int q = 0;
bool escape = false;
while (p < n && q < m) {
if (searchInto[p] == tosearch[q]) {
if (tosearch[q] == '/' && !escape) {
++q;
} else {
++p; ++q;
}
escape = false;
} else if (!escape && tosearch[q] == '*') {
++q;
while (q < m && p < n && searchInto[p] != tosearch[q]) ++p;
escape = false;
} else if (!escape && tosearch[q] == '?') {
++p; ++q;
escape = false;
} else if (tosearch[q] == '/' && !escape) {
escape = true;
++q;
} else break;
}
if (q == m) {
return i;
}
if (q == m - 1 && tosearch[q] == '*') {
if (q > 0 && tosearch[q - 1] == '/') continue;
else return i;
}
}
return ans;
}
int main()
{
string searchInto, tosearch;
cout<< "Enter string:";
getline(cin, searchInto);
cout << "Looking for :";
getline(cin, tosearch);
if (tosearch.length() < 2)
{
char ch = tosearch.at(0);
cout << "Found at: " <<charsearch(searchInto, ch) << endl;
cout << "Used Char" << endl;
}
else
cout << "Found at: " <<substr(searchInto, tosearch) << endl;
return 0;
}

To find a character in a string, you have two interfaces.
std::string::find will return the position of a character you find:
auto pos = yourStr.find('h');
char myChar = yourStr[pos];
If the character does not exist, then std::string::npos will be returned as the std::size_t returned for position.
stl algorithm std::find, in header algorithm returns an iterator:
auto it = std::find(yourStr.begin(), yourStr.end(), 'h');
char myChar = *it;
If the character does not exist, then it == yourStr.end().

There are some silly mistakes in your CharSearch method. First of all, You have to break the loop when you got your target character. And most importantly you are not assigning x when you are finding the target. Furthermore, there is extra increment of value i inside the loop. I have modified the function. Please check it below
int charsearch(string searchInto, char ch, int start = 0) {
int x = -1;
long n = searchInto.length();
for (int i = start; i < n; i++)
{
cout << ch;
if (searchInto[i] == ch)
{
x = i; // previously written as i = x which is wrong
break; // loop should break when you find the target
}
}
cout<< x;
return x;
}
Please note that,you can either also use find method of string or std::find of algorithm to search in string.

You need to make changes as per this code
int charsearch(string searchInto, char ch, int start = 0)
{
int x = -1; // : change, if return -1, means not found
long n = searchInto.length();
for (int i = start; i < n; i++) // : change
{
cout << ch;
if (searchInto[i] == ch)
{
x = i; // : change
break; // : change
}
}
cout<< x;
return x;
}
Note : This function will return 1st match.

Related

issue with pointers and count

I need to build a code where it takes a 2d array of char and checks if its palindrome the second function uses the first one to see how many arrays are palindrome my issue with the code is that every time I get count is 0; I know the issue is in the second function but don't know where
#include <iostream>
using namespace std;
int CountPal(char M[][5], int rows);
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
}
int main() {
int x;
cout << "please enter the number of rows " << endl;
cin >> x;
char M[5][5];
cout << "before test" << endl;
cout << CountPal(M, x) << endl;
cout << "After test" << endl;
system("pause");
}
int CountPal(char M[][5], int rows) {
int count = 0;
cout << "please enter the string " << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 5; j++) {
cin >> M[i][j];
}
for(int i = 0; i < rows; i++) {
char* S;
S = &M[i][0];
if(pal(S) == 1) count++;
}
}
return count;
}
I think your problem is in int pal(char* S) function. You want it to return 1 if a given string of your 2d array is a palindrome to up your count by 1. And anything other than 1 would be non palindrome string.
So i think you should add a return statement after the end of your int pal(char* S) function like this;
int pal(char* S) {
char *p, *start, flag = 1;
p = S;
while(*p != NULL) {
++p;
}
--p;
for(start = S; p >= start && flag;) {
if(*p == *start) {
--p;
start++;
} else
flag = 0;
}
return flag;
}
You could even change your function to bool data type. It's more proper because you only want to return "true" or "false" values.

isPalindrome homework exercise

Write a program that uses the function isPalindrome given in Example 6-6 (Palindrome). Test your program on the following strings:
madam, abba, 22, 67876, 444244, trymeuemyrt
Modify the function isPalindrome of Example 6-6 so that when determining whether a string is a palindrome, cases are ignored, that is, uppercase and lowercase letters are considered the same.
The isPalindrome function from Example 6-6 has been included below for your convenience.
bool isPalindrome(string str)
{
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length – 1 – i]) {
return false;
} // if
} // for loop
return true;
}// isPalindrome
Your program should print a message indicating if a string is a palindrome:
madam is a palindrome
My program so far is this
#include <iostream>
#include <string.h>
using namespace std;
int main () {
bool isPalindrome (string str);
string str;
int length = str.length();
cout << "Enter a string: ";
getline (cin,str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length -1 -i]) {
cout << str << "Is not a Palindrome";
return false;
} else if (str[i] == str[length -1 -i] && toupper(str[i]) != islower(str[i])) {
cout << str << "Is a Palindrome";
} // for loop
return true;
}
}
I do not know what im doing wrong I sent everything to make sure it matches the word backwards and then when it is true it will return true. I am very to new to programming and I am sorry if my code is a little sloppy.
This is a modification of your code. It wasn't too logical that you were declaring the function inside so i just put it outside.
#include <iostream>
#include <string.h>
using namespace std;
bool isPalindrome(string str) {
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length -1 -i]) {
cout << str << "Is not a Palindrome";
return false;
} else if (str[i] == str[length -1 -i] && toupper(str[i]) != islower(str[i])) {
cout << str << "Is a Palindrome";
} // for loop
return true;
}
return false;
}
int main () {
string str;
cout << "Enter a string: ";
getline (cin,str);
isPalindrome(str);
}
public static bool IsPalindrome(string value)
{
int i = 0;
int j = value.Length - 1;
while (true)
{
if (i > j)
{
return true;
}
char a = value[i];
char b = value[j];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
i++;
j--;
}
}
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 1000
bool isPalindrome(int x){
int c[MAX];
int i = 0;
int j;
int k = 0;
bool z;
if(x < 0){
return false;
}
while (x != 0){
int r = x % 10;
c[i] = r;
i++;
x = x / 10;
}
for (j = i - 1; j > -1; j--) {
printf("%d ", c[j]);
}
for(k = 0; k <= (i / 2); k++){
if(c[k] == c[i - k - 1]){
z = true;
}
else
{
z = false;
}
}
return z;
}

Parenthesized Expression (Infix and Post fix) Conversion and Evaluation

I have the below code working fine but outputs only 2nd input, not 1st or 3rd.
My code should get fully parenthesized expression from console and convert it to postfix expression and then that postfix expression should be evaluated in modulo 10.Therefore, all results (including intermediate results) are single decimal digits in {0, 1, …, 9}. I need to store only single digits in the stack.
My inputs and outputs are shown in below.I only got 2nd input correctly.
Please advise.
Expression 1: (((2+(5^2))+7)
Answer:
252^+7+
4 in modulo 10
Expression 2: ((((2+5)*7)+((9*3)*2))^2)
Answer:
25+7*93*2*+2^
9 in modulo 10
Expression 3: ((((2*3)*(4*6))*7)+(((7+8)+9)*((2+4)*((7+8)+9))))
Answer:
23*46*7*789++24+78+9+**+
4 in modulo 10
My code:
#include <iostream>
#include <string>
#include<sstream>
using namespace std;
class STACK {
private:
char *s;
int N;
public:
STACK(int maxN) {
s = new char[maxN];
N = 0;
}
int empty() const {
return N == 0;
}
void push(char item) {
s[N++] = item;
}
char pop() {
return s[--N];
}
};
int main() {
string infixExpr;
string postfixExpr = "";
cout << "Enter infix expression:" << endl;
cin >> infixExpr; //converting to postfix read from the input
int N = infixExpr.size(); //strncpy(a, infixExpr.c_str(), N);
STACK ops(N);
char ch;
for (int i = 0; i < N; i++) {
if (infixExpr[i] == ')')
{
ch = ops.pop();
postfixExpr.push_back(ch);
}
if ((infixExpr[i] == '+') || (infixExpr[i] == '*') || (infixExpr[i] == '^'))
ops.push(infixExpr[i]);
if ((infixExpr[i] >= '0') && (infixExpr[i] <= '9'))
{
//cout << infixExpr[i] << " ";
postfixExpr.push_back(infixExpr[i]);
}
}
cout <<"Answer :"<<endl;
cout <<postfixExpr <<endl; //evaluate post fix expression
N = postfixExpr.size();
STACK save(N);
int result;
int num;
int count = 0;
string temp = "";
for (int i = 0; i < N; i++) {
// cout << " Expr[i] " << postfixExpr[i] << endl;
if (postfixExpr[i] == '+')
save.push((save.pop() + save.pop()) % 10);
if (postfixExpr[i] == '*')
save.push((save.pop() * save.pop()) % 10);
if (postfixExpr[i] == '^') {
count = save.pop() - '0';
num = save.pop() - '0'; //cout << result << "- " <<"-" <<count<<endl;
result = 1;
for(int j = 1; j <= count; j++)
{
result = result * num;
result = result % 10;
}
stringstream convert;
convert << result;//add the value of Number to the characters in the stream
temp = convert.str();//set Result to the content of the stream
save.push(temp[0]);
}
if ((postfixExpr[i] >= '0') && (postfixExpr[i] <= '9'))
{
save.push(postfixExpr[i]);
}
}
cout << save.pop() <<" in module 10"<< endl;
return 1;
}

How do I add a character to a string after each iteration of a loop c++

I'm trying to create a roman calculator that reads from a file. I'm struggling to figure out how to add characters to a string. I would like a new character to be added with no spaces after each iteration of a loop this would be used when the program is writing the answer.
I've tried this.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
string convert_to_Roman(int num)
{
string c;
while (num>0)
{
string c;
if (num >= 1000)
{
num = num - 1000;
return c='M';
}
else if (num >= 500 && num<1000)
{
num = num -500;
return c = 'D';
}
else if (num >= 100 && num<500)
{
num = num -100;
return c= 'C';
}
else if (num >= 50 && num<100)
{
num = num - 50;
return c = 'L';
}
else if (num >= 10 && num<50)
{
num = num - 10;
return c = 'X';
}
else if (num >= 5 && num<10)
{
num = num - 5;
return c = 'V';
}
else if (num<5)
{
num = num - 1;
return c = 'I';
}
c +=c;
//cout<<"answer= "<< + answer<<endl;
}
cout << c;
}
int convert_from_Roman(string & s)
{
int num=0;
int length; //length of string
length = s.length();
for (int i = 0; i < length; i++)
{
char c = s[i];
int digit;
if (c == 'M')
{
return num = 1000;
}
else if (c == 'D')
{
return num = 500;
}
else if (c == 'C')
{
return num = 100;
}
else if (c == 'L')
{
return num = 50;
}
else if (c == 'X')
{
return num = 10;
}
else if (c == 'V')
{
return num = 5;
}
else if (c == 'I')
{
return num = 1;
}
else
{
cout << "invalid entry" << endl;
continue;
}
num += num;
}
cout<<num<<endl;
}
void print_Result(/* figure out the calling sequence */)
{
// fill in your code
}
// Note the call by reference parameters:
string finalAnswer()
{
string operand1, operand2;
char oper;
cout << "enter operation: " << endl;
cin >> operand1 >> operand2 >> oper;
int value1, value2, answer;
value1 = convert_from_Roman(operand1);
value2 = convert_from_Roman(operand2);
switch (oper)
{
case '+':
{
answer = value1 + value2;
break;
}
case '-':
{
answer = value1 - value2;
break;
}
case '*':
{
answer = value1*value2;
break;
}
case '/':
{
answer = value1 / value2;
break;
}
default:
{
cout << "bad operator : " << oper << endl;
return;
}
string answerInRoman = convert_to_Roman(answer);
return answerInRoman;
cout << "answer= " << answerInRoman << " (" << answer << ") " << endl;
}
You can simply use concatenation like so.
char addThis;
string toThis;
addThis = 'I';
toThis = "V";
toThis += addThis;
or
toThis = toThis + addThis;
If you want to place the number somewhere other than the end of a string, you can access the elements of a string like an array toThis[0] is equal to 'V'.
If you are not using std::string as mentioned below, this can be done with a dynamic character array and an insert method that resizes the array properly as follows:
#include <iostream>
using namespace std;
void addCharToArray(char * & array, int physicalSize, int & logicalSize, char addThis)
{
char * tempPtr;
if (physicalSize == logicalSize)
{
tempPtr = new char[logicalSize + physicalSize];
for (int i = 0; i < logicalSize; i++)
{
tempPtr[i] = array[i];
}
delete [] array;
array = tempPtr;
}
array[logicalSize] = addThis;
logicalSize++;
}
int main()
{
char addThis = 'I';
char * toThis;
int physicalSize = 1;
int logicalSize = 0;
toThis = new char[physicalSize];
toThis[0] = 'V';
logicalSize++;
//when adding into the array, you must perform a check to see if you must add memory
addCharToArray(toThis, physicalSize, logicalSize, addThis);
for (int i = 0; i < logicalSize; i++)
{
cout << toThis[i];
}
cout << endl;
return 0;
}

how to check whether 2 strings are rotations to each other ?

Given 2 strings, design a function that can check whether they are rotations to each other without making any changes on them ? The return value is boolean.
e.g ABCD, ABDC, they are not rotations. return false
ABCD, CDAB or DABC are rotations. return true.
My solution:
shift one of them to right or left one position and then compare them at each iteration.
If they are not equal at all iterations, return false. Otherwise, return true.
It is O(n). Are there other more efficient solutions ?
What if the contents of them cannot be changed ?
thanks
Concatenate the given string with the given string.
Search for the target string in the concatenated string.
Example:
Given = CDAB
After step 1, Concatenated = CDABCDAB
After step 2, Success CDABCDAB
^^^^
Rather than shifting one of them, it might be more efficient to use two index variables. Start one at 0 each time and the other at each of the possible positions (0 to N-1) and increment it mod N.
If you can't modify the strings, just take the first character of string1 and compare it to each character of string2. When you get a match, compare the second char of string1 to the next char of string2, and so on.
Pseudocode:
len = strlen(string1);
len2 = strlen(string2);
if( len != len2 )
printf("Nope.");
for( int i2=0; i2 < len; i2++ ) {
for( int i1=0; i1<len; i1++ ) {
if( string1[i1] != string2[(i2+i1)%len] )
break;
}
if( i1 == len ) {
print("Yup.");
break;
}
}
A simple one would be:
(s1+s1).find(s2) != string::npos && s1.size() == s2.size();
#include <iostream>
#include <cstring>
#include<string>
using namespace std;
void CompareString(string, string, int);
int ComputeStringLength(string str);
int main()
{
string str = ""; string str1 = ""; int len = 0, len1 = 0;
cout << "\nenter string ";
cin >> str;
cout << "\nenter string 2 to compare:- ";
cin >> str1;
len = ComputeStringLength(str);
len1 = ComputeStringLength(str1);
if (len == len1)
CompareString(str, str1, len);
else
cout << "rotation not possible";
getchar();
return 0;
}
int ComputeStringLength(string str)
{
int len = 0;
for (int i = 0; str[i] != '\0'; i++)
{
len++;
}
return len;
}
void CompareString(string str, string str1, int n)
{
int index = 0, flag = 0, curr_index = 0, count1 = 0, flagj = 0;
for (int i = 0; i<n; i++)
{
for (int j = flagj; j<n; j++)
{
if (str[i] == str1[j])
{
index = j;
flagj =j;
count1++;
flag++;
if (flag == 1)
{
curr_index = index;
}
break;
}
}
}
int temp = count1;
if (count1 != n)
{
if (curr_index>=0)
{
int k = 0;
for (int i = n - 1; i>n - curr_index - 1; i--)
{
if (str[i] == str1[k])
{
temp++;
k++;
}
}
}
if (temp == n)
{
cout << "\n\nstring is same after rotation";
}
else
{
cout << "\n\nstring is not same after rotation";
}
}
else
{
cout << "\n\nstring is same after rotation";
}
}
https://dsconceptuals.blogspot.in/2016/10/a-program-to-check-if-strings-are.html