I cannot figure out why this function won't work.
I want to return a string what is trimmed from the char array passed into the function at the index where it finds an identifying char. Is there something obvious I'm missing? As it is, this only returns the first letter of the input char[]...
#include <iostream>
#include <cstring>
using namespace std;
string trim(char in[], char token){
char A[300];
for(int i = 0; i < strlen(in); i++){
if(in[i] != token){
A[i] = in[i];
} else
A[i] = '\0';
break;
}
return A;
}
int main()
{ char statement[] = {"weight of car is ?1 ton"};
cout << trim(statement, '?') << endl;
return 0;
}
Because you break; in the first iteration. Use a block to avoid it.
#include <iostream>
#include <cstring>
using namespace std;
string trim(char in[], char token){
char A[300];
for(int i = 0; i < strlen(in); i++){
if(in[i] != token){
A[i] = in[i];
} else {
A[i] = '\0';
break;
}
}
return A;
}
int main()
{ char statement[] = {"weight of car is ?1 ton"};
cout << trim(statement, '?') << endl;
return 0;
}
Note that calling strlen too many times isn't a good idea.
This should be better:
#include <iostream>
using namespace std;
string trim(char in[], char token){
char A[300];
bool token_found = false;
for(int i = 0; in[i] != '\0'; i++){
if(in[i] != token){
A[i] = in[i];
} else {
A[i] = '\0';
token_found = true;
break;
}
}
if (token_found) {
return A;
} else {
return in;
}
}
int main()
{ char statement[] = {"weight of car is ?1 ton"};
cout << trim(statement, '?') << endl;
return 0;
}
Related
Please tell me what is wrong in my approach.
#include <iostream>
#include <string>
using namespace std;
string datatype(string x) {
for (int k = 0; k < strlen(x.c_str());) {
for (int i = 0; i < 10; i++) {
char z = i;
if (x[k] == z) {
k++;
}
else {
return "string";
}
}
}
return "int";
}
int main() {
string inp;
cin >> inp;
cout << datatype(inp);
}
Whatever i enter, it always returns "string".
I have seen the other questions posted here but please tell me what is wrong in my approach.
The standard library has the isdigit function that tells you if the char is a digit.
Here you check that each char of your input is a digit, as soon as a character that is not a digit is found string is returned, else int.
For example 1234 returns int, sdf returns string.
string datatype(string str) {
for (unsigned char c : str) {
if (!isdigit(c)) {
return "string";
}
}
return "int";
}
Edit:
This solution also handles leading - and +. It will return int for -10 and +10 but returns string for +1+1 or -10+10.
string datatype(string str) {
if (str.size() == 1) {
return isdigit(str[0]) ? "int" : "string";
}
bool isInt = true;
for (int i = 1; i < str.size(); i++) {
isInt = isInt && isdigit(static_cast<unsigned char>(str[i]));
if (!isInt) {
break;
}
}
if (isInt) {
unsigned char c = str[0];
isInt = isInt && (c == '-' || c == '+' || isdigit(c));
}
return isInt ? "int" : "string";
}
First of all Include (cstring) as header since x.c_str is not in iostream and string. Then,
When you are doing char z=i; here you are not storing the character equivalent of i in z but the ascii value of i.
Next, You are returning string at the first mismatch between i and x[k]. You should return string if you cannot find a match with any of the possible 10 digits.
You can have a look at the modified code.
#include <iostream>
#include<cstring>
#include <string>
using namespace std;
string datatype(string x) {
for (int k = 0; k < strlen(x.c_str());k++) {
int flag=0;
for (int i = 0; i < 10; i++) {
// char z = i;
if ((x[k]-'0') == i || (k==0 && x[k]=='-')) {
flag=1;
break;
}
}
if(flag==0)
return "string";
}
return "int";
}
int main() {
string inp;
cin >> inp;
cout << datatype(inp);
}
I was trying to implement suffix tree using c++ by looking at some examples online. I am running into pointer issue and I am not able to fix it. Any help is greatly appreciated.
/*
* Implement suffix array to print the maximum suffix substring in a string
* Algorithm:
* Build a suffix tree and find the lowest node with multiple children
*
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <ctype.h>
using namespace std;
struct node{
char ch;
node* next[26];
int treeHeight;
int childCount;
int end = 0;
};
void insertSuffixIntoTree(node*& root, string suffix){
if (suffix.size() == 0){
return;
}
char c = suffix[0];
int index = tolower(c) - 'a';
if (root->next[index] == NULL){
root->next[index] = new node();
for (int k = 0; k < 26; k++){
root->next[index]->next[k] = NULL;
}
root->next[index]->ch = tolower(c);
if (suffix.size() == 1){
root->next[index]->end = 1;
}
}
suffix.erase(suffix.begin());
insertSuffixIntoTree(root->next[index], suffix);
}
void buildSuffixTree(node* root, string str){
if (root == NULL) cout << "CRAP" << endl;
for (int i = str.size() - 1; i >= 0; i--){
string suffix = str.substr(i);
cout << "suffix is " << suffix << endl;
insertSuffixIntoTree(root, suffix);
}
}
void printSuffixTree(node* root, string str){
if (root->end){
cout << str << endl;
return;
}
for (int i = 0; i<26; i++){
while (root->next[i]){
str += root->ch;
return printSuffixTree(root->next[i],str);
}
}
}
int main() {
string str;
node* suffixRoot = new node();
suffixRoot->ch = ' ';
for (int i = 0; i < 26; i++){
suffixRoot->next[i] = NULL;
}
cout << "enter the string" << endl;
cin >> str;
buildSuffixTree(suffixRoot, str);
//string result = findMaxSuffix(suffixRoot,str);
//cout<<"result is "<<result<<endl;
string result = "";
printSuffixTree(suffixRoot,result);
getchar();
return 0;
}
The error is happening at insertIntoSuffixTree method inside buildSuffixTree method. My understanding is I am loosing my pointer address I started with. Any idea on how to get around this issue?
Sorry for any inconvenience. I fixed the code as seen below:
/*
* Implement suffix array to print the maximum suffix substring in a string
* Algorithm:
* Build a suffix tree and find the lowest node with multiple children
*
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <ctype.h>
using namespace std;
struct node{
char ch;
node* next[26];
int treeHeight;
int childCount;
int end = 0;
};
void insertSuffixIntoTree(node* root, string suffix){
if (suffix.size() == 0){
return;
}
char c = suffix[0];
int index = tolower(c) - 'a';
if (root->next[index] == NULL){
root->next[index] = new node();
for (int k = 0; k < 26; k++){
root->next[index]->next[k] = NULL;
}
root->next[index]->ch = tolower(c);
if (suffix.size() == 1){
root->next[index]->end = 1;
}
}
suffix.erase(suffix.begin());
insertSuffixIntoTree(root->next[index], suffix);
}
void buildSuffixTree(node* root, string str){
if (root == NULL) cout << "CRAP" << endl;
for (int i = str.size() - 1; i >= 0; i--){
string suffix = str.substr(i);
cout << "suffix is " << suffix << endl;
insertSuffixIntoTree(root, suffix);
}
}
bool checkEmptyVector(node * leaf){
for (int i = 0; i < 26; i++){
if (leaf->next[i] != NULL){
return false;
}
}
return true;
}
void printSuffixTree(node* root, string str){
if (root->end){
cout << str << endl;
}
if (checkEmptyVector(root)){
return;
}
for (int i = 0; i<26; i++){
//cout << "inside for loop, i is " << i << endl;
while (root->next[i]){
str += root->next[i]->ch;
printSuffixTree(root->next[i],str);
break;
}
}
}
int main() {
string str;
node* suffixRoot = new node();
suffixRoot->ch = ' ';
for (int i = 0; i < 26; i++){
suffixRoot->next[i] = NULL;
}
cout << "enter the string" << endl;
cin >> str;
buildSuffixTree(suffixRoot, str);
//string result = findMaxSuffix(suffixRoot,str);
//cout<<"result is "<<result<<endl;
string result = "";
printSuffixTree(suffixRoot,result);
getchar();
return 0;
}
wanted to read only nums from file & store them in array.i don't know file handling. please help me out.
#include iostream conio.h
#stdio.h string fstream;
using namespace std;
int main()
{
ifstream myfile("ashishdata.txt");//file open
char c;
char arr[100];
int i=0;
// read data from file
while (myfile.get(c))
{
if(isdigit(c) || c=='.' )
{
arr[i] = c;
i++;
}
}
arr[i]='\0';//mark end of array
myfile.close();//file closed
int k;
k=strlen(arr);
//parsing string
int newarr[100];
int m=0;
string(s);
for(i=0;i<=k;i++)
{
s.erase();
while(arr[i] != '.')
{
s+=arr[i];
i++;
}
newarr[m]=atoi(s.c_str());
m++;
}
newarr[m]='\0';
//printing newarray
i=0;
while(newarr[i]!='\0')
{
cout<<newarr[i]<<'\t';
i++;
}
cout<<endl;
getch();
return(0);
}
Try this:
filename.txt:
4545.454
sds
65.65.6.65656
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;
int main() {
char c;
char arr[100];
size_t i = 0;
// read data from file
ifstream myfile;
myfile.open("filename.txt", ios::in);
while (!myfile.eof()) {
myfile >> c;
if (isdigit(c) || c == '.') {
arr[i] = c;
i++;
}
}
arr[i] = '\0'; // mark end of array
myfile.close(); // file closed
size_t k = strlen(arr);
// parsing string
int newarr[100];
int m = 0;
string s;
for (i = 0; i <= k; i++) {
s.erase();
while (arr[i] != '.') {
s += arr[i++];
}
newarr[m++] = atoi(s.c_str());
}
newarr[m] = '\0';
// printing newarray
i = 0;
while (newarr[i] != '\0') {
cout << newarr[i++] << '\t';
}
return 0;
}
I'm 100% sure my code is incorrectly determining the size of the array
When I put in hello as the input and set strArray[5] it works correctly. But the problem is I don't know how big the size of the input will be so I just put 80 (since that's the max it could be)
Here's my code.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
main()
{
string str1;
char strArray[80];
cout << "Enter string: ";
getline(cin, str1);
transform(str1.begin(), str1.end(), str1.begin(), ::tolower);
str1.erase(remove(str1.begin(),str1.end(),' '),str1.end());
for(int i = 0;i < str1.length(); i++)
{
if(str1[i] == ',' || str1[i] == '.')
{
str1.erase(i,1);
}
}
for(int i=0;i<str1.length();i++)
{
strArray[i] = str1[i];
}
char tempChar;
for(int i = 0; i < (sizeof(strArray)/sizeof(*strArray))-1; i++)
{
for(int j = 0; j < (sizeof(strArray)/sizeof(*strArray)-1); j++)
{
if(strArray[j+1] < strArray[j])
{
tempChar = strArray[j];
strArray[j] = strArray[j+1];
strArray[j+1] = tempChar;
}
}
}
cout << strArray << endl;
return 0;
}
You can just make strArray a string. Or, if you must use a char array, you should dynamically allocate the char array with char *strArray = new char[str1.length()]. In this case, don't forget to delete [] strArray; when done.
Examples:
char test1[] = " ";
char test2[] = " hello z";
char test3[] = "hello world ";
char test4[] = "x y z ";
Results:
" "
" olleh z"
"olleh dlrow "
"x y z "
The problem:
Reverse every world in a string, ignore the spaces.
The following is my code. The basic idea is to scan the string, when
finding a word, then reverse it. The complexity of the algorithm is
O(n), where n is the length of the string.
How do verify it? Is there a better solution?
void reverse_word(char* s, char* e)
{
while (s < e)
{
char tmp = *s;
*s = *e;
*e = tmp;
++s;
--e;
}
}
char* word_start_index(char* p)
{
while ((*p != '\0') && (*p == ' '))
{
++p;
}
if (*p == '\0')
return NULL;
else
return p;
}
char* word_end_index(char* p)
{
while ((*p != '\0') && (*p != ' '))
{
++p;
}
return p-1;
}
void reverse_string(char* s)
{
char* s_w = NULL;
char* e_w = NULL;
char* runner = s;
while (*runner != '\0')
{
char* cur_word_s = word_start_index(runner);
if (cur_word_s == NULL)
break;
char* cur_word_e = word_end_index(cur_word_s);
reverse_word(cur_word_s, cur_word_e);
runner = cur_word_e+1;
}
}
Your code seems correct, but it's plain C. In C++, using the same approach, it could look something like this:
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>
int main()
{
std::string str = " cat cow dog wolf lobster";
std::string result;
auto it = str.begin();
while (it != str.end()) {
while (it != str.end() && isspace(*it)) {
result += *it;
++it;
}
auto begin = it;
while (it != str.end() && !isspace(*it)) {
++it;
}
auto end = it;
result.append(std::reverse_iterator<decltype(end)>(end),
std::reverse_iterator<decltype(begin)>(begin));
// if you want to modify original string instead, just do this:
std::reverse(begin, end);
}
std::cout << result <<'\n';
}
In-place, ANSI C89.
#include <ctype.h>
#include <stdio.h>
void reverse(char *s) {
int i = 0, j, k;
while (1) {
while (isspace(s[i])) i++;
if (!s[i]) return;
for (j = i; !isspace(s[j]) && s[j] != '\0'; j++);
for (k = 0; k < (j - i) / 2; k++) {
char t = s[i + k];
s[i + k] = s[j - k - 1];
s[j - k - 1] = t;
}
i = j;
}
}
int main(int argc, char**argv) {
if (argc != 2) return 1;
reverse(argv[1]);
printf("%s\n", argv[1]);
return 0;
}
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char s[89];
cout << "enter\n";
gets(s);
int k;
int p = strlen(s);
strcat(s," ");
for(int i=0; i <= p; i++)
{
if(s[i]==' ')
{
for (k = i-1; (k != -1) && (s[k] != ' '); k--)
cout<<s[k];
cout<<" ";
}
}
return 0;
}
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[100],a[10],s[100]=" ";
int i,j;
cout<<"enter a string";
cin.getline(str,100);
strcat(s,str);
for(i=0;s[i]!='\0';i++)
{
if(s[i]==' '&&s[i+1]!=' '&&s[i+1]!='\0')
{
cout<<" ";
if(i==0)cout<<"\b";
j=i+1;
while(s[j]!=' '&&s[j]!='\0')
{
j++;
}
j--;
while(s[j]!=' ')
{
cout<<s[j];
j--;
}
}
else if(s[i]==' ')
{
cout<<" ";
if(i==0)cout<<"\b";
}
}
return 0;
}
#include <iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
void Reverse_Each(char st[60])
{
int i,j,k=0,p=0,l;
char sr[60];
l=strlen(st);
for(i=0;i<=l;i++) {
if((st[i]==' ')||(st[i]=='\0')) {
for(j=i-1;j>=p;j--) {
sr[k]=st[j]; k++;
}
sr[k]=' '; k++; p=i+1;}
}
for(i=0;i<p;i++)
cout<<sr[i];
}
int main(){
char s[60];
gets(s);
Reverse_Each(s);
return 0;
}