0% found this document useful (0 votes)
7 views7 pages

C++ String Manipulation Functions

The document contains multiple C++ code examples demonstrating string manipulation functions such as substring extraction, insertion, deletion, replacement, palindrome checking, camel case formatting, and sequence pattern identification (arithmetic or geometric). Each example includes a main function that tests the respective functionality with sample inputs. The code snippets illustrate various programming concepts and string handling techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

C++ String Manipulation Functions

The document contains multiple C++ code examples demonstrating string manipulation functions such as substring extraction, insertion, deletion, replacement, palindrome checking, camel case formatting, and sequence pattern identification (arithmetic or geometric). Each example includes a main function that tests the respective functionality with sample inputs. The code snippets illustrate various programming concepts and string handling techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Substring:
#include <iostream>
using namespace std;
string mysub(string s1, int a, int b)
{
string result="";
for(int i=a;i<a+b;i++)
{
result+=s1[i];
}
return result;
}

int main() {
string s1="helloworld";
cout<<mysub(s1,2,3);
return 0;
}

2. INSERT:
#include <iostream>
using namespace std;
string mysub(string s1, int pos, int len)
{
string result="";
for(int i=pos;i<pos+len;i++)
{
result+=s1[i];
}
return result;
}

string insert (string t, int a, string s)


{
return mysub(t, 0, a) + s + mysub(t,a,[Link]()-a);
}

int main() {
string s1="helloworld";
cout<<insert(s1,3,"xyz");
return 0;
}

3. DELETE:
#include <iostream>
using namespace std;
string mysub(string s1, int pos, int len)
{
string result="";
for(int i=pos;i<pos+len;i++)
{
result+=s1[i];
}
return result;
}

string delet (string t, int pos, int len)


{
return mysub(t, 0, pos) + mysub(t,pos+len,[Link]()-pos-len);
}

int main() {
string s1="helloworld";
cout<<delet(s1,3,4);
return 0;
}

4. REPLACE:
#include <iostream>
using namespace std;
string mysub(string s1, int pos, int len)
{
string result="";
for(int i=pos;i<pos+len;i++)
{
result+=s1[i];
}
return result;
}
string insert (string t, int a, string s)
{
return mysub(t, 0, a) + s + mysub(t,a,[Link]()-a);
}

string delet (string t, int pos, int len)


{
return mysub(t, 0, pos) + mysub(t,pos+len,[Link]()-pos-len);
}

string replace(string t, string p1, string p2)


{
int pos=[Link](p1);
if(pos!=-1){
t= delet(t, pos, [Link]());
t= insert(t, pos, p2 );
return t;
}
else
return t;
}

int main() {
string s1="xabyabz";
cout<<replace(s1,"ba","c");
return 0;
}

5. Palindrome

Have the function Palindrome(str) take the str parameter being passed and return the string true if
the parameter is a palindrome, (the string is the same forward as it is backward) otherwise return
the string false. For example: "racecar" is also "racecar" backwards. Punctuation and numbers
will not be part of the string.

Examples

Input: "never odd or even" Output: true

Input: "eye" Output: true


Solution:

#include<iostream>
#include<string>
using namespace std;
string Palindrome(string s1)
{
int len=[Link]();
for(int i=0;i<len; i++)
{
if(s1[i]==' ')
[Link](i,1); //to delete any substring use erase(postion, length)
}
string s2=s1;
for(int i=0;i<[Link]()/2; i++)
{
swap(s1[i], s1[[Link]()-i-1]);
}
if(s2==s1)
return "true";
else
return "false";
}
int main()
{
string s1;
getline(cin,s1);
cout<<Palindrome(s1);
}

6. Camel Case
Have the function CamelCase(s1) take the s1 parameter being passed and return it in proper
camel case format where the first letter of each word is capitalized (excluding the first letter).
The string will only contain letters and some combination of delimiter punctuation characters
separating each word. For example: if str is "BOB loves-coding" then your program should
return the string bobLovesCoding.

Examples
Input: "cats AND*Dogs-are Awesome" Output: catsAndDogsAreAwesome
Input: "a b c d-e-f%g" Output: aBCDEFG
Solution:
#include<iostream>
#include<string>
using namespace std;
string CamelCase(string s1)
{
string result="";
bool captalize= false;

for(int i=0;i<[Link](); i++)


{
if(!isalpha(s1[i]))
{
captalize= true;
}
else{
if(captalize==true){
result+=toupper(s1[i]);
captalize=false;
}
else
result+=tolower(s1[i]);
}
}
return result;
}
int main()
{
string s1;
getline(cin,s1);
cout<<CamelCase(s1);
}

7. Arith Geo
Have the function ArithGeo(arr) take the array of numbers stored in arr and return the string
"Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a
geometric pattern. If the sequence doesn't follow either pattern return -1. An arithmetic sequence
is one where the difference between each of the numbers is consistent, whereas in a geometric
sequence, each term after the first is multiplied by some constant or common ratio. Arithmetic
example: [2, 4, 6, 8] and Geometric example: [2, 6, 18, 54]. Negative numbers may be entered as
parameters, 0 will not be entered, and no array will contain all the same elements.

Examples
Input: [5,10,15] Output: Arithmetic
Input: [2,4,16,24] Output: -1

Solution:
#include <iostream>
using namespace std;

string ArithGeo(int arr[], int n) {


bool isArithmetic = true;
int diff = arr[1] - arr[0];
for (int i = 2; i < n; i++) {
if (arr[i] - arr[i - 1] != diff) {
isArithmetic = false;
break;
}
}

// Check if it's a geometric sequence


bool isGeometric = true;
int ratio = arr[1] / arr[0];
for (int i = 2; i < n; i++) {
if (arr[i] / arr[i - 1] != ratio) {
isGeometric = false;
break;
}
}

if (isArithmetic) {
return "Arithmetic";
} else if (isGeometric) {
return "Geometric";
} else {
return "-1";
}
}

int main() {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>> arr[i];

cout << ArithGeo(arr, n) << endl;


return 0;
}

Common questions

Powered by AI

The 'mysub' function is used to extract a substring from a given string. It takes a string 's1', a starting position 'pos', and a length 'len' as parameters. The function initializes an empty result string and appends each character from the start position up to the specified length to this result string, which it then returns. This function is called within other operations like 'insert' and 'delete' to facilitate string manipulations .

The 'ArithGeo' function would return a value of '-1' when the sequence of numbers does not follow either an arithmetic pattern (constant difference between consecutive terms) or a geometric pattern (each term is a constant multiple of the previous one). For example, given the input [2, 4, 16, 24], neither the differences nor the ratios between the terms are consistent, leading to a return value of '-1' .

In the 'CamelCase' function, punctuation and special characters act as word delimiters. When a non-alphabetic character is encountered, the function sets a flag 'captalize' to true, ensuring the next alphabetic character is capitalized, transitioning the format from a previous word or character separated by punctuation. The effect is that each word following a punctuation or space will start with an uppercase letter, except the very first word, which is converted to lowercase .

The 'CamelCase' function initially processes characters by defaulting them to lowercase using 'tolower'. It tracks whether the preceding character was a non-alphabetic separator through a boolean flag 'captalize'. With this flag, the next alphabetic character is converted to uppercase via 'toupper', ensuring subsequent words start with a capital letter. The first word is treated as lowercase by initializing 'captalize' as false before processing begins, ensuring it remains in lowercase initially .

The 'replace' function will successfully substitute one substring with another if the first occurrence of the substring 'p1' is found within the string 't'. The function utilizes the 'find' method to locate the starting position of 'p1'. If 'p1' is found (i.e., the position is not -1), the function uses 'delet' to remove 'p1' from the string and then 'insert' to insert 'p2' at the same position. If 'p1' is not found, the function returns the original string without modification .

The output of the 'insert' function when called with arguments "helloworld", 3, "xyz" is "helxyzloworld". The function works by first extracting the substring from index 0 to 3 (not inclusive) from the string "helloworld" using the 'mysub' function, resulting in "hel". It then appends the string "xyz" to this result, followed by appending another substring from index 3 to the end of the original string. This final operation is effectively inserting "xyz" at index 3 .

To optimize the performance of the string manipulation functions 'mysub', 'insert', and 'delet', several strategies can be employed: First, replacing iterative concatenation with direct memory allocation to avoid repeated dynamic memory allocation. Second, leveraging C++ standard library functions such as 'substr', which are often more optimized. Third, reducing redundant operations within functions, like minimizing repeated string assignments or conditions. Lastly, considering the use of in-place operations or character pointers to directly manipulate string buffer memory, which can reduce overhead .

Changing the parameter ordering in the 'delet' function, particularly swapping 'pos' and 'len', would disrupt the intended logic of removing a substring from a string. For instance, if 'delet(s1, 4, 2)' is supposed to remove two characters starting at index 4, reversing the parameters to 'delet(s1, 2, 4)' might lead to logic errors or unintended behaviors, potentially causing incorrect removal of characters if attempted without modifying other parts of the code. This change requires all calls and relevant logic checks to be adjusted accordingly .

The phrase "never odd or even" is identified as a palindrome by the solution provided in the document. The function first removes spaces from the string, then it swaps characters from start to end to create a reverse version of the original string. It compares this reversed string with the original one (without spaces) to determine equality, which confirms if it is a palindrome. Since the modified string matches its reverse, the function returns 'true' .

The 'ArithGeo' function can handle negative values, but its logic hinges on straightforward integer operations for arithmetic differences and multiplicative ratios. This can be problematic for division involving negative numbers or specific fractions that might yield inaccurate integer division results. Additionally, it assumes valid sequence inputs without validating each numerical step properly. Complex or non-standard sequences, varying data types, or those with zero values (which it explicitly avoids) could lead to undefined behaviors or incorrect outputs due to its simplistic pattern detection mechanism .

You might also like