I have to use a function that takes two strings and one integer value that tell the position at which the second string is to be entered in the first.
For Example:
String 1 = "I have apple"
String 2 = "an "
position = 6,
Output:
String 1 = "I have an apple"
Here's my code, so far:
#include <iostream>
using namespace std;
const int SIZE=102;
void insertString(char str1[ ],char str2[ ],int position);
int main()
{
char str1[SIZE], str2[SIZE];
int position,i=0,j=0;
cout<<"Enter string 1 of atmost 50 characters:\n";
cin.getline(str1,SIZE/2);
cout<<"Enter string 2 of atmost 50 characters:\n";
cin.getline(str2,SIZE/2);
cout<<"Enter Position number where String 2 is to be inserted: ";
cin>>position;
while(position<0||position>50)
{
cout<<"Invalid input. Enter a positive Position number less than 51\n"<<
"where String 2 is to be inserted: ";
cin>>position;
}
insertString(str1,str2,position);
cout<<"Modified string 1: "<<str1<<endl;
system("pause");
return 0;
}
/******************************************************************************
Definition of function insertString:
This function takes two C-string in form of character arrays and one integer value
as parameters
It inserts String 2 in String 1 on the required position.
*******************************************************************************/
void insertString(char str1[ ],char str2[ ],int position)
{
char temp[SIZE];
int i,j,countStr2;
for(j=0;j<SIZE&&str2[j]!=0;j++)
countStr2=j;
for(i=position,j=0;i<SIZE,j<=countStr2; i++,j++)
{
temp[i]=str1[i];
str1[i]=str2[j];
}
}
This logic overwrites some characters of string 1. What should I do?
Any help will be appreciated.
#include<cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and inserts str2 in str1 at the specified position in a
newStr, then returns the new string as apointer*/
char* insertString(const char str1[ ],const char str2[ ],const int& position)
{
int shiftedPos=position-1;
int str2Size=strlen(str2);
int str1Size=strlen(str1);
int newSize=str2Size+str1Size+1;
char* newStr=new char[newSize];
for(int i=0; i<shiftedPos; i++) newStr[i]=str1[i];
for(int i=0; i<str2Size; i++) newStr[shiftedPos+i]=str2[i];
for(int i=0; i<newSize; i++) newStr[shiftedPos+str2Size+i]=str1[shiftedPos+i];
newStr[newSize]='\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout<<insertString(str1,str2, 8);
return 0;
}
Another code to perform exactly as you wanted
#include<iostream>
#include<cstring>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and that the memory allocated by str1 >= the len(str1)+len(str2)+1.
It inserts str2 in str1 at the specified position in str1*/
void insertString(char str1[ ], char str2[ ], int position)
{
int str1Size=strlen(str1);
int str2Size=strlen(str2);
int newSize=str2Size+str1Size+1;
int cppPosition=position-1;
for(int i=str1Size; i>=cppPosition; i--) str1[i+str2Size]=str1[i];
for(int i=0; i<str2Size; i++) str1[cppPosition+i]=str2[i];
str1[newSize]='\0';
}
int main(){
char str1[50]= "I have apple";
char str2[50] = "an ";
insertString(str1,str2, 8);
std::cout<<str1;
return 0;
}
If you have to implement the void insertString(char str1[ ],char str2[ ],int position) function, you don't have many options here.
One of the possible solutions is to shift the characters in the first string to the right to make space for the second string to be inserted there.
Such an approach might look like this:
void insertString(char str1[], char str2[], int position) {
const int len1 = strlen(str1);
const int len2 = strlen(str2);
// First, shift all the characters from the given position to the right by `len2` positions:
for (int i = 0; i < len1 - position; ++i) {
str1[len1 - i - 1 + len2] = str1[len1 - i - 1];
}
// Then insert the second string in the given position:
for (int i = 0; i < len2; ++i) {
str1[position + i] = str2[i];
}
// Make sure to create a new terminator since the
// previous one got overwritten by the the first loop
str1[len1 + len2 + 1] = 0;
}
LIVE DEMO
Note, that this is potentially insecure! If there is not enough space in the str1 array to store another strlen(str2) characters, it will lead to a buffer overflow.
Way more secure option would be to allocate a new buffer for your new concatenated string on the heap, but for the sake of your assignment, this should suffice.
Since you're using C++, you should avoid this approach altogether in any production code, replacing char arrays with std::string, for example. But I've already read in the comments that you can't use it just yet.
Assuming you can use <string>, then I would put std::string::substr to use:
#include <string>
std::string originalString = "I have apple"; // original string
std::string insert = " an "; // added space beforehand for the new word to be inserted
int position = 6; // index where the new word would be inserted
int remainingStringSize = originalString.length() - position - 1; // count how many characters remain from the position you're inserting
std::string combinedString = originalString.substr(0, 6) + insert + originalString.substr(position +1, remainingStringSize); // resulting combined string
Words of caution, you obviously would need to check the following:
That index position is within the length of the original string where you wish to insert
That the remaining # of characters is more than 0
Related
As part of my homework assignment, I have to split a char[] by its indices. So for example, the main function looks like:
int main()
{
char str[] = "A string to be split into given number of parts";
int split_size;
cout << "Enter the size of the part: ";
cin >> split_size;
int size = sizeof(str) / sizeof(str[0]);
SplitString(str, split_size, size);
int wait;
cin >> wait;
return 0;
}
Then using the function SplitString, the first x elements are printed, new line, then the next.
My first idea, was to use two for loops. One loops through the splits (i.e. if there are 4 splits, the range on this loop is 0 to 3), then the second loops through the split itself, iterating over the array elements.
My SplitString() function looks like this:
void SplitString(char str[], int split_size, int size) {
int parts = size / split_size;
for (int i = 0; i < parts; i++) {
for (int j = 0; j < split_size; j++) {
j = split_size * i;
cout << str[j];
}
cout << endl;
}
}
Is there an easier way to do this? I know in Python, you can use the arr[1:] to grab a range of elements from the array. Is there anything similar in C++? Is there some flaw in my logic? Is there something wrong with my code?
cout comes with a write function that takes a pointer and a size argument.
for (int i = 0; i < parts; i++) {
cout.write (str+i*split_size, split_size)
cout << endl;
}
Note that the code above does not check if the string is actually long enough. If the total size is not equal the split_size times a whole number, you will have to add an additional check.
Also, note that this:
int size = sizeof(str) / sizeof(str[0]);
can be written as:
int size = sizeof(str);
instead because the size of a char is always 1.
You can use std::string for this. Alternatively, if your compiler supports C++17, you can use std::string_view as the first argument of SplitString to avoid unnecessary copying.
#include <algorithm>
#include <iostream>
#include <string>
void SplitString(std::string s, std::size_t split_size)
{
while(!s.empty())
{
auto size = std::min(split_size, s.size());
std::cout << s.substr(0, size) << '\n';
s = s.substr(size, std::string::npos);
}
}
int main()
{
char str[] = "A string to be split into given number of parts";
int split_size = 5;
SplitString(str, split_size);
return 0;
}
Live example.
Hello I'm new to c++ and can't figure out why my code is doing this. I've scoured across the internet and can't find the solution I need. I appreciate all the help. The line that's giving me the problem is when I'm calling the function. According to visual studios it states that "argument of type 'char*' is incompatible with parameter of type 'char**'". It's referring to newArr.
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include "stdafx.h"
using namespace std;
bool isPalindrome(char *newArr[], int);
//int i = 0;
//char phrase;
//char c;
bool palindrome;
bool tOf;
int numb;
char c;
const int length = 80; //const so that it can't be changed
char inarr[length]; //array set to a const length of 80
char newArr[length]; //array that will have no spaces
string str;
int main()
{
cout << "This program tests if a word/phrase is palindrome.\n\n";
cout << "Please enter your phrase (just letters and blanks,
please):\n\n";
cin.getline(inarr, length);
//cout << array; //spits out the array
str = inarr; //turn into string
numb = str.length();
//cout << numb << "\n"; //how many characters in array
for (int i = 0; i < (numb / 2) + 1; i++)
{
for (int j = 0; j < (numb / 2) + 1; j++)
{
newArr[j] = inarr[i]; //from old array to new array
c = newArr[j];
newArr[j] = toupper(c); //change to all upper case
//cout << newArr[j];
i += 2; //goes to every other index to skip space in string
}
}
tOf = isPalindrome(newArr, numb); //calling of function
if (tOf == true) //the response to true or false
{
cout << "\nYes, the phrase is a palindrome!";
}
else
{
cout << "\nNo, the phrase is not a palindrome!";
}
return 0;
}
bool isPalindrome(char *newArr[], int numb) //function to determine true or
false
{
for (int i = 0; i < (numb / 2) + 1; i++) //within the array...
{
if (newArr[i] != newArr[(numb / 2) - i]) //if first index != last
and etc (iterates)
{
palindrome = false;
}
else
{
palindrome = true;
}
}
return palindrome;
}
You're trying to pass newArr (a char *) into isPalindrome() (which takes a char **). This is what "argument of type 'char*' is incompatible with parameter of type 'char**'" means.
To fix this, simply pass in a char **; you can do this by passing in the address of newArr instead of newArr itself:
tOf = isPalindrome(&newArr, numb); //calling of function
Brief
Change the function signature (both definition and declaration) of the function to
bool isPalindrome(char* newArr, int numb);
Call it
tOf = isPalindrome(newArr, numb);
Detail
If you call isPalindrome(newArr, numb). you are passing address of the first element either &newArr[0] . So you are function defination should be able to pick the address of the element. hence *newArr
Further your function will validate the details by using array arithmetic. which is all right .
Output
$ ./a.out
This program tests if a word/phrase is palindrome.
Please enter your phrase (just letters and blanks, please):
Palindrome
No, the phrase is not a palindrome!
$ ./a.out
This program tests if a word/phrase is palindrome.
Please enter your phrase (just letters and blanks, please):
YeseY
Yes, the phrase is a palindrome!
$
How can I erase the first N-th characters in a given string and append them in the end. For example if we have
abracadabra
and we shift the first 4 characters to the end then we should get
cadabraabra
Instead of earsing them from the front which is expensive there is another way. We can rotate them in place which is a single O(N) operation. In this case you want to rotate to the left so we would use
std::string text = "abracadabra";
std::rotate(text.begin(), text.begin() + N, text.end());
In the above example if N is 4 then you get
cadabraabra
Live Example
You can try an old-fashioned double loop, one char at a time.
#include "string.h"
#include "stdio.h"
int main() {
char ex_string[] = "abracadabra";
int pos = 4;
char a;
int i, j;
size_t length = strlen(ex_string);
for (j = 0; j < pos; j++) {
a = ex_string[0];
for (i = 0; i < length - 1; i++) {
ex_string[i] = ex_string[i + 1];
}
ex_string[length-1]=a;
}
printf("%s", ex_string);
}
string str = "abracadabra" //lets say
int n;
cin>>n;
string temp;
str.cpy(temp,0,n-1);
str.earse(str.begin(),str.begin()+n-1);
str+=temp;
Reference
string::erase
string::copy
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str;
cin >> str;
int number;
cin >> number;
string erasedString = str;
string remainingString = str.substr(number + 1, strlen(str));
erasedString.erase(0, number);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
getline(cin , s) ; #input of string from user
int counter = 0;
int max_word = -1;
int len = s.length(); #length of string
string max = " ";
string counter_word = " ";
for (int i = 0; i < len; i++)
{
if(s[i] != ' ')
{
counter++;
}
if(s[i] == ' ' || i == len - 1)
{
if(counter > max_word)
{
max_word = counter;
//handling end of string.
if(i == len - 1)
max = s.substr(i + 1 - max_word, max_word); #sub string command that prints the longest word
else
max = s.substr(i - max_word, max_word);
}
counter = 0;
}
}
cout << max_word << " " << max << endl; #output
return 0;
}
The current output is '4 This' on entering the string "This is cool".
How do I get it to print '4 This; Cool' ?
On running it in Linux through the terminal, it gives me the error
" terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::substr Aborted (core dumped) "
If I have understood you correctly then you mean the following
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string s;
std::getline( std::cin, s );
std::string::size_type max_size;
std::string max_word;
std::string word;
std::istringstream is( s );
max_size = 0;
while ( is >> word )
{
if ( max_size < word.size() )
{
max_size = word.size();
max_word = word;
}
else if ( max_size == word.size() )
{
max_word += "; ";
max_word += word;
}
}
std::cout << max_size << ' ' << max_word << std::endl;
}
If to enter string
This is cool
then the output will be
4 This; cool
The basic idea here is to add each character to a temporary (initially empty) string until a space is encountered. At each instance of a space, the length of the temporary string is compared to the length of the "maxword" string, which is updated if it is found to be longer. The temporary string is emptied (reset to null using '\0') before proceeding to the next character in the input string.
#include <iostream>
#include <string>
using namespace std;
string LongestWord(string str) {
string tempstring;
string maxword;
int len = str.length();
for (int i = 0; i<=len; i++) {
if (tempstring.length()>maxword.length())
{
maxword=tempstring;
}
if (str[i]!=' ')
{
tempstring=tempstring+str[i];
}
else
{
tempstring='\0';
}
}
return maxword;
}
int main() {
cout << LongestWord(gets(stdin));
return 0;
}
#include <iostream>
using namespace std;
string longestWordInSentence(string str) {
// algorithm to count the number of words in the above string literal/ sentence
int words = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
words++;
}
}
// incrementing the words variable by one as the above algorithm does not take into account the last word, so we are incrementing
// it here manually just for the sake of cracking this problem
words += 1; // words = 5
// words would be the size of the array during initialization since this array appends only the words of the above string
// and not the spaces. So the size of the array would be equal to the number of words in the above sentence
string strWords[words];
// this algorithm appends individual words in the array strWords
short counter = 0;
for (short i = 0; i < str.length(); i++) {
strWords[counter] += str[i];
// incrementing the counter variable as the iterating variable i loops over a space character just so it does not count
// the space as well and appends it in the array
if (str[i] == ' ') {
counter++;
}
}
// algorithm to find the longest word in the strWords array
int sizeArray = sizeof(strWords) / sizeof(strWords[0]); // length of the strWords array
int longest = strWords[0].length(); // intializing a variable and setting it to the length of the first word in the strWords array
string longestWord = ""; // this will store the longest word in the above string
for (int i = 0; i < sizeArray; i++) { // looping over the strWords array
if (strWords[i].length() > longest) {
longest = strWords[i].length();
longestWord = strWords[i]; // updating the value of the longestWord variable with every loop iteration if the length of the proceeding word is greater than the length of the preceeding word
}
}
return longestWord; // return the longest word
}
int main() {
string x = "I love solving algorithms";
cout << longestWordInSentence(x);
return 0;
}
I have explained every line of the code in great detail. Please refer to the comments in front of every line of code. Here is a generalized approach:
Count the number of words in the given sentence
Initialize a string array and set the size of the array equal to the number of words in the sentence
Append the words of the given sentence to the array
Loop through the array and apply the algorithm of finding the longest word in the string. It is similar to finding the longest integer in an array of integers.
Return the longest word.
My original solution contained a bug: If you were to input 2 words of length n and 1 word of length n + k, then it would output those three words.
You should make a separate if condition to check whether the word length is the same as before, if yes, then you can append "; " and the other word.
This is what I would do:
Change if(counter > max_word) to if(counter >= max_word) so words of the same length are also taken into account.
Make the max string by default (so "" instead of " "). (See next point)
Add an if condition in the if(counter >= max_word)second if condition to see if the max string is not empty, and if it's not empty append "; "
Changing max = to max += so that it appends the words (in the second condition)
Wouldn't it be easier for you to split the whole line into a vector of string ?
Then you could ask the length of each element of the string and then print them. Because right now you still have all the words in a single string making each individual word hard to analyse.
It would also be hard, as you requested, to print all the words with the same length if you use a single string.
EDIT :
Start by looping through your whole input
Keep the greater length of word between the current one and the previously saved
Make a substring for each word and push_back it into a vector
Print the length of the bigger word
Loop through the vector and print each word of that size.
Look the following website for all references about vectors. dont forget to #include
www.cplusplus.com/reference/vector/vector/
#include <iostream>
#include <vector>
#include <string>
void LongestWord(std::string &str){
std::string workingWord = "";
std::string maxWord = "";
for (int i = 0; i < str.size(); i++){
if(str[i] != ' ')
workingWord += str[i];
else
workingWord = "";
if (workingWord.size() > maxWord.size())
maxWord = workingWord;
}
std::cout << maxWord;
}
int main(){
std::string str;
std::cout << "Enter a string:";
getline(std::cin, str);
LongestWord(str);
std::cout << std::endl;
return 0;
}
Source: http://www.cplusplus.com/forum/beginner/31169/
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,a;
char ch;
int len,mlen=0;
getline(cin,s);
char* token=strtok(&s[0]," ");
string r;
while(token!=NULL)
{
r=token;
len=r.size();
if(mlen<len)
{
mlen=len;
a=token;
}
token = strtok(NULL, " ");
}
cout<<a;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
string str;
getline(cin,str);
cin.ignore();
int len =str.length();`
int current_len=0,max_len=0;
int initial=0,start=0;
int i=0;
while(1)
{
if(i==len+2)
{break;}
if(str[i]==' '|| i==len+1)
{
if(current_len>max_len)
{
initial=start;
max_len=current_len;
}
current_len=0;
start=i+1;
}
else
{
current_len++;
}
i++;
}
for (int i = 0; i < max_len; i++)
{
cout<<str[i+initial];
}
cout<<endl<<max_len<<endl;
return 0 ;
}
i had my midterm today. this was the first question. i could not solve this.
the exact requirement is as follows :
we have to determine if a string , lets say , "DA" is subset of another, "ABCD". the number of letters is crucial, for exmaple "DAD" is not a subset of "ABCD". because "D" is repeated twice whereas in the parent string "D" occurs once. also it can be assumed that that no. of letters of parent string is always equal to or greater than the other.
i thought a lot about this. my approach towards this was that i will compare the characters of the to-be-found substring with the parent string. if a match is found i will store its index in a third array. so in the end i will have the arrays of characters of the parent array which matched characters from the other array.this is how far i have been able to get.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char array[] = "ABCD";
char array1[] = "AB";
int size = strlen(array);
int size1 = strlen(array1);
int temp[size];
int no = 0;
for (int i = 0; i< size1; i++)
{
for (int j = 0; j< size; j++)
{
if (array1[i]==array[j])
{
for(int k = 0; k<size ; k++)
{
if (temp[k] != j)
{
temp[no] = j;
no++;
}
}
}
}
}
for (int i = 0; i<size; i++)
cout<<endl<<temp[i]<<" ";
return 0;
}
kindly help in solving this and do tel me if you have another approach to this.
also, are arrays or a string a better approach to this problem.
i am writing in c++
thanks in advance
(I recently used this as a quiz for my students but we're using Groovy and Java.)
A simple aproach: create a copy of the string ("ABCD") and strike matched letters so that they won't match again, for example after matching a "D" and "A", the copy would be "_BC_" and it would not match another "D".
You can also count the number of occurrences of each letter in each string and make sure the count of each letter in the second string is less than or equal to the count of each letter in the first string. This might be better in the case where you want to compare multiple potential substrings to a single collection of letters (e.g. comparing all the words in the dictionary to the current letters in Boggle).
This code will do that. It has the primary limitation that it only works with strings containing the 26 capital letters in the English alphabet. But it gets the idea across.
#include <iostream>
#include <cstring>
using namespace std;
void stringToArray(char *theString, int *countArray) {
int stringLength = strlen(theString);
for (int i=0; i<26; i++) {
countArray[i] = 0;
}
for (int i=0; i<stringLength; i++) {
countArray[theString[i] - 'A']++;
}
}
bool arrayIsSubset(int *superCount, int *subCount) {
//returns true if subCount is a subset of superCount
bool isSubset = true;
for (int i=0; i<26 && isSubset; i++) {
isSubset = subCount[i] <= superCount[i];
}
return isSubset;
}
int main()
{
char array[] = "ABCD";
char array1[] = "AB";
char array2[] = "ABB";
int letterCount[26], letterCount1[26], letterCount2[26];
stringToArray(array, letterCount);
stringToArray(array1, letterCount1);
stringToArray(array2, letterCount2);
cout << "array1 is " << (arrayIsSubset(letterCount, letterCount1) ? "" : "not ") << "a subset" << endl;
cout << "array2 is " << (arrayIsSubset(letterCount, letterCount2) ? "" : "not ") << "a subset" << endl;
}
produces:
array1 is a subset
array2 is not a subset