Reverse String in C++
Reverse String in C++
Here’s a simple C++ program to reverse a string that includes spaces. This example uses basic concepts,
making it beginner-friendly:
Code:
cpp
`#include <iostream>
#include <string>
#include <algorithm> // For std::reverse
int main() {
// Input the string
std::string inputString;
std::cout << "Enter a string: ";
std::getline(std::cin, inputString); // Use getline to handle spaces
return 0;
}
`
How it Works:
1. Input with spaces: The `std::getline` function is used to read a full line of text, including spaces.
2. Reversing the string: The `std::reverse` function from `<algorithm>` is applied to reverse the
string in place.
3. Output: The reversed string is printed.
Example Output:
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/38
Here’s a beginner-friendly way to reverse a string in C++ without using any STL functions:
Code:
cpp
`#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Use cin.getline to handle spaces
return 0;
}
`
How It Works:
1. Input Handling: The `cin.getline` function allows reading a string with spaces up to a maximum
length of 100 characters.
2. String Length Calculation: A `while` loop calculates the string length by iterating until the null
terminator (`\0`) is reached.
3. Manual Reversal: A `for` loop swaps characters from the start and end of the string until the
middle is reached.
4. Output: The reversed string is printed directly.
Example Output:
csharp
This method avoids using STL and demonstrates basic array and loop manipulation.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/38
i dont want any inbuilt functin want to prepare for interview
Understood! Here's a pure implementation of reversing a string in C++ without using any inbuilt
functions:
Code:
cpp
`#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read input including spaces
// Move pointers
start++;
end--;
}
return 0;
}
`
Explanation:
1. Input Handling:
`cin.getline(inputString, 100)` reads a string including spaces.
No other function is used for input manipulation.
2. Calculate Length Manually:
A `while` loop increments a counter (`length`) until the null terminator (`\0`) is reached.
3. Reverse Without STL:
Two pointers (`start` and `end`) are used to traverse the string.
Swap the characters at `start` and `end` using a temporary variable.
Move the pointers inward until they meet.
4. Output Result:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/38
After the reversal, the modified array is printed as the reversed string.
Example Output:
kotlin
This implementation focuses entirely on manual logic and avoids all inbuilt functions, making it a great
practice for coding interviews.
Here are a few more beginner-level ways to reverse a string in C++ without using any inbuilt
functions. These examples highlight different approaches while keeping the logic simple.
cpp
`#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100], reversedString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read input including spaces
return 0;
}
`
Explanation:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/38
The original string remains unchanged.
cpp
`#include <iostream>
using namespace std;
// Recursive call
reverseString(str, start + 1, end - 1);
}
int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100);
return 0;
}
`
Explanation:
This code uses a recursive function to reverse the string by swapping characters at the start and
end.
The function continues to swap until the pointers meet in the middle.
cpp
`#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100], stack[100];
cout << "Enter a string: ";
cin.getline(inputString, 100);
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/38
// Push characters onto the stack
int length = 0, top = -1;
while (inputString[length] != '\0') {
stack[++top] = inputString[length];
length++;
}
return 0;
}
`
Explanation:
cpp
`#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100);
// Reverse by swapping
for (int i = 0; i < length / 2; i++) {
inputString[i] = inputString[i] + inputString[length - i - 1];
inputString[length - i - 1] = inputString[i] - inputString[length - i - 1];
inputString[i] = inputString[i] - inputString[length - i - 1];
}
return 0;
}
`
Explanation:
This uses arithmetic operations (addition and subtraction) to swap characters without using an
extra variable.
It’s a fun way to explore swapping logic.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/38
Practice Tip:
Experiment with these variations to get a deeper understanding of string manipulation. Each approach
demonstrates different thought processes, which is useful for interviews.
Here's a very simple C++ code to reverse a string, without any prebuilt functions, aimed at beginners:
cpp
`#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read string with spaces
return 0;
}
`
Explanation:
1. Input Handling:
The string is read using `cin.getline`, allowing spaces in the input.
No built-in function is used to manipulate the input.
2. Length Calculation:
A `while` loop calculates the string length by iterating until the null character (`\0`).
3. Reversal Logic:
A `for` loop swaps characters from the start and end of the string.
A temporary variable (`temp`) is used to hold a character during the swap.
4. Output:
The reversed string is printed after modification.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/38
Example Run:
csharp
#include <iostream>
using namespace std;
int main() {
// Input the string
char inputString[100], reversedString[100];
cout << "Enter a string: ";
cin.getline(inputString, 100); // Read input including spaces
return 0;
} in this i want to use string instead of chr
To use `std::string` instead of character arrays, you can modify the code as follows:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/38
cpp
`#include <iostream>
#include <string> // Include the string library
using namespace std;
int main() {
// Input the string
string inputString, reversedString;
cout << "Enter a string: ";
getline(cin, inputString); // Use getline to read a string including spaces
return 0;
}
`
Key Changes:
1. Using `std::string`:
Replaced `char inputString[100]` with `std::string inputString`.
Replaced `char reversedString[100]` with `std::string reversedString`.
2. Resizing `reversedString`:
Before filling `reversedString`, it is resized using `reversedString.resize(length)` to ensure it
has enough capacity.
3. `getline` for Input:
`getline(cin, inputString)` is used to handle input with spaces.
Example Run:
csharp
This approach uses `std::string` while avoiding advanced functions, keeping it beginner-friendly.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/38
reversedString.resize(length); // Resize the string to match the input length
for (int i = 0; i < length; i++) {
reversedString[i] = inputString[length - i - 1];
} use something else instead of this
If you want to avoid directly resizing and manually assigning characters to `reversedString`, you can
build the reversed string step-by-step by appending characters in reverse order. Here's how:
Modified Code:
cpp
`#include <iostream>
#include <string>
using namespace std;
int main() {
// Input the string
string inputString, reversedString;
cout << "Enter a string: ";
getline(cin, inputString); // Use getline to handle spaces
return 0;
}
`
Changes Made:
1. Avoid `resize`:
Instead of pre-resizing `reversedString`, we build it character by character.
2. Appending Characters:
Used `reversedString += inputString[i];` to append characters in reverse order.
Example Run:
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/38
This approach is simple and uses basic string concatenation, which is easy to understand for beginners.
If you want to avoid using `reversedString += inputString[i];`, you can insert each character at the
front of the `reversedString` instead of appending it. Here's how:
Updated Code:
cpp
`#include <iostream>
#include <string>
using namespace std;
int main() {
// Input the string
string inputString, reversedString;
cout << "Enter a string: ";
getline(cin, inputString); // Use getline to handle spaces
return 0;
}
`
Explanation of Change:
Example Run:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/38
csharp
This method demonstrates another way of constructing a reversed string, suitable for practice and
understanding string operations better.
Explanation:
1. `inputString[i]`:
This accesses the character at index `i` in the string `inputString`.
For example, if `inputString = "Hello"` and `i = 1`, then `inputString[i]` is `'e'`.
2. `reversedString += ...`:
This is shorthand for `reversedString = reversedString + ...;`.
The `+=` operator takes the current value of `reversedString`, adds the character
`inputString[i]` to it, and stores the result back in `reversedString`.
3. Step-by-Step Behavior:
When the loop executes, each character from `inputString` (in reverse order) is added to
`reversedString`.
Example:
cpp
`inputString = "Hello";
reversedString starts as ""; // Initially empty
Why is it Useful?
Ease of Use: The `+=` operator simplifies appending characters to the string without needing
explicit resizing or indexing.
Dynamic Growth: The `reversedString` dynamically grows as more characters are added.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/38
Key Notes:
The `+=` operator works for both `char` and `std::string`. If `inputString[i]` is a `char`, it's
implicitly converted to a single-character string and appended.
Internally, `std::string` manages memory dynamically, so you don't need to worry about resizing
when using `+=`.
Example Behavior:
cpp
// Appending step-by-step
reversedString += inputString[4]; // reversedString = "d"
reversedString += inputString[3]; // reversedString = "dl"
reversedString += inputString[2]; // reversedString = "dlr"
reversedString += inputString[1]; // reversedString = "dlro"
reversedString += inputString[0]; // reversedString = "dlroW"
To find the two largest numbers in an array or a list of numbers, you can use a simple algorithm that
compares elements without sorting the array. Here's how you can do it:
cpp
`#include <iostream>
using namespace std;
int main() {
int arr[100], n;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/38
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest; // Update second largest
largest = arr[i]; // Update largest
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest if it's smaller than largest
}
}
return 0;
}
`
Explanation
1. Initialize Variables:
and `secondLargest` are initialized to a very small value (`-1e9` or another minimum
`largest`
value depending on the problem).
2. Traverse the Array:
If the current number is greater than `largest`, update `secondLargest` to `largest`, and
update `largest` to the current number.
If the current number is not equal to `largest` but greater than `secondLargest`, update
`secondLargest`.
3. Edge Case Handling:
If all numbers in the array are the same or there is only one number, output a message
indicating that a second largest number does not exist.
Example Run
Input:
yaml
Output:
csharp
Key Notes
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/38
Time Complexity: The algorithm runs in O(n) time as it traverses the array once.
Space Complexity: It uses only a few variables, so the space complexity is O(1).
Handles Duplicates: The condition `arr[i] != largest` ensures that duplicates are ignored when
finding the second largest.
This loop is the core of the algorithm to find the largest and second-largest numbers in an array. Let's
break it down step by step:
Key Variables
1. `largest`:
Holds the largest number found so far.
Starts with a very small value (e.g., `-1e9` or any minimum placeholder value).
2. `secondLargest`:
Holds the second largest number found so far.
Also starts with a very small value.
cpp
Step-by-Step Explanation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/38
Update `secondLargest` to the value of `largest`. This ensures the previous largest value
becomes the second-largest value.
Update `largest` to the current element `arr[i]`.
2. `else if (arr[i] > secondLargest && arr[i] != largest)`
If the current element is not larger than `largest`, this condition is checked.
It ensures that the current element is:
Greater than the current `secondLargest`.
Not equal to the current `largest` (to avoid duplicate handling).
3. Ignore Smaller Values:
If `arr[i]` is neither greater than `largest` nor greater than `secondLargest`, the loop simply
moves to the next element without making any changes.
Example Walkthrough
Final Output:
Largest: `9`
Second Largest: `5`
Key Points
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/38
i still didnt understood
No problem! Let me break it down further with a detailed explanation and analogy so it's easy to follow.
We want to find the largest and second-largest numbers in an array in one pass. Here's how the loop
works step-by-step:
Conceptual Explanation
Imagine you are given a list of numbers one by one, and you have two placeholders:
Code Explanation
cpp
Iteration 1:
`i = 0`, `arr[i] = 3`
Check: `arr[i] > largest` → `3 > -∞` (True)
Update `secondLargest = largest = -∞`
Update `largest = 3`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/38
Now: `largest = 3`, `secondLargest = -∞`
Iteration 2:
`i = 1`, `arr[i] = 7`
Check: `arr[i] > largest` → `7 > 3` (True)
Update `secondLargest = largest = 3`
Update `largest = 7`
Now: `largest = 7`, `secondLargest = 3`
Iteration 3:
`i = 2`, `arr[i] = 2`
Check: `arr[i] > largest` → `2 > 7` (False)
Check: `arr[i] > secondLargest` → `2 > 3` (False)
No changes.
Now: `largest = 7`, `secondLargest = 3`
Iteration 4:
`i = 3`, `arr[i] = 5`
Check: `arr[i] > largest` → `5 > 7` (False)
Check: `arr[i] > secondLargest` → `5 > 3` (True)
Update `secondLargest = 5`
Now: `largest = 7`, `secondLargest = 5`
Iteration 5:
`i = 4`, `arr[i] = 9`
Check: `arr[i] > largest` → `9 > 7` (True)
Update `secondLargest = largest = 7`
Update `largest = 9`
Now: `largest = 9`, `secondLargest = 7`
Iteration 6:
`i = 5`, `arr[i] = 8`
Check: `arr[i] > largest` → `8 > 9` (False)
Check: `arr[i] > secondLargest` → `8 > 7` (True)
Update `secondLargest = 8`
Now: `largest = 9`, `secondLargest = 8`
Final Output
`largest = 9`
`secondLargest = 8`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/38
Simpler Analogy
1. If a contestant beats the champion, the current champion becomes the runner-up, and the new
contestant is the champion.
2. If the contestant doesn't beat the champion but beats the runner-up, they take the runner-up spot.
By the end of the contest, you’ll have the champion (largest) and the runner-up (second largest).
Key Takeaways
First `if`: Updates both `largest` and `secondLargest` if a new largest number is found.
Second `else if`: Updates only `secondLargest` if a number is greater than the current second
largest but not the largest.
To check whether a number is a palindrome, you can reverse the number and compare it with the
original. If they are the same, the number is a palindrome.
Here's a beginner-friendly code:
cpp
`#include <iostream>
using namespace std;
int main() {
int number, originalNumber, reversedNumber = 0, remainder;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/38
}
return 0;
}
`
How It Works:
Example Runs:
Example 1:
Input: `121`
Output: `121 is a palindrome.`
Example 2:
Input: `123`
Output: `123 is not a palindrome.`
Example 3:
Input: `12321`
Output: `12321 is a palindrome.`
Key Points:
This code works for both positive and negative numbers. If you want to exclude negatives, you can
add a check:
cpp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/38
}
`
The logic is efficient and runs in O(d), where d is the number of digits in the input.
while (number != 0) {
remainder = number % 10; // Get the last digit
reversedNumber = reversedNumber * 10 + remainder; // Append digit to reversed number
number = number / 10; // Remove the last digit
} explain this
This block of code is used to reverse the digits of a given number. Let me explain it step by step:
Variables
1. `number`:
Holds the current value of the number being reversed. It is reduced step-by-step in the loop.
2. `remainder`:
Stores the last digit of the number during each iteration.
3. `reversedNumber`:
Builds the reversed version of the number by appending digits one by one.
cpp
`while (number != 0)
`
cpp
The `%` (modulus) operator gives the remainder when `number` is divided by 10.
This extracts the last digit of the number.
Example:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/38
If `number = 123`, then `remainder = 123 % 10 = 3`.
If `number = 45`, then `remainder = 45 % 10 = 5`.
cpp
Example:
cpp
Example:
Example Walkthrough
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/38
2. `reversedNumber = reversedNumber * 10 + remainder`: Shift `reversedNumber` left and append the
last digit.
3. `number = number / 10`: Remove the last digit from `number` to prepare for the next iteration.
To check whether a number is an Armstrong number, you need to calculate the sum of the cubes (or
powers corresponding to the number of digits) of its digits and compare it to the original number. If
they are equal, the number is an Armstrong number.
cpp
`#include <iostream>
#include <cmath> // For pow() function
using namespace std;
int main() {
int number, originalNumber, remainder, result = 0, digits = 0;
return 0;
}
`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/38
Explanation
Example Runs
Example 1:
Input: `153`
13 + 53 + 33 = 1 + 125 + 27 = 153
Output: `153 is an Armstrong number.`
Example 2:
Input: `9474`
Example 3:
Input: `123`
13 + 23 + 33 = 1 + 8 + 27 = 36
Output: `123 is not an Armstrong number.`
Key Notes
1. Armstrong Numbers:
For 3-digit numbers, they are numbers like 153, 370, 371, 407.
For 4-digit numbers, examples include 9474.
2. Edge Cases:
Single-digit numbers are always Armstrong numbers because n1 = n.
3. Efficiency:
This code works efficiently for small numbers. For very large numbers, performance can be
slower due to the `pow` function.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/38
explain everything also why orginal number and numner n all
Sure! Let’s go through every part of the Armstrong number code step-by-step, explaining the logic, why
variables like `originalNumber` and `number` are used, and how everything works.
An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the
number of digits.
For example:
Code Overview
cpp
`#include <iostream>
#include <cmath> // For pow() function
using namespace std;
int main() {
int number, originalNumber, remainder, result = 0, digits = 0;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/38
return 0;
}
`
Variable Explanations
1. `number`:
This is the user input number.
We keep this variable unchanged because we need it at the end to compare the computed
result to the original number.
2. `originalNumber`:
Used as a temporary copy of `number`.
This variable is modified during the process of counting digits and calculating the sum of
powers.
Why use `originalNumber`?
If we directly modify `number`, we lose the original value for the final comparison.
By working with `originalNumber`, the input `number` remains intact for the final check.
3. `digits`:
Stores the count of digits in the number. For example:
`153` has 3 digits.
`9474` has 4 digits.
This count is important because each digit must be raised to this power to calculate the
Armstrong number.
4. `remainder`:
Stores the last digit of the number at each step of the loop.
Extracted using the modulus operator (`%`).
5. `result`:
Accumulates the sum of each digit raised to the power of `digits`.
At the end of the program, this is compared to the original `number`.
cpp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/38
cpp
`while (originalNumber != 0) {
originalNumber = originalNumber / 10;
digits++;
}
`
Divide `originalNumber` by 10 repeatedly until it becomes `0`. Each division removes one digit from
the number.
Increment `digits` with each step to count how many digits were removed.
3. Reset `originalNumber`
cpp
`originalNumber = number;
`
Restore `originalNumber` to the input `number`, so it can be used for further calculations.
cpp
`while (originalNumber != 0) {
remainder = originalNumber % 10; // Get the last digit
result += pow(remainder, digits); // Add digit^digits to the result
originalNumber = originalNumber / 10; // Remove the last digit
}
`
Iteration 1:
`remainder = 9474 % 10 = 4`
`result = 0 + pow(4, 4) = 256`
`originalNumber = 9474 / 10 = 947`
Iteration 2:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/38
`remainder = 947 % 10 = 7`
`result = 256 + pow(7, 4) = 2401 + 256 = 2657`
`originalNumber = 947 / 10 = 94`
Iteration 3:
`remainder = 94 % 10 = 4`
`result = 2657 + pow(4, 4) = 256 + 2657 = 2913`
`originalNumber = 94 / 10 = 9`
Iteration 4:
`remainder = 9 % 10 = 9`
`result = 2913 + pow(9, 4) = 6561 + 2913 = 9474`
`originalNumber = 9 / 10 = 0`
cpp
Key Points
Here’s how to find the minimum and maximum values in an array in C++. I'll also provide a detailed
explanation of the logic.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/38
C++ Code: Finding Min and Max in an Array
cpp
`#include <iostream>
using namespace std;
int main() {
int n;
return 0;
}
`
Explanation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/38
5. Output the Results
Once the loop ends, `min` contains the smallest value, and `max` contains the largest value in
the array.
Example Run
Input:
yaml
Execution:
Output:
yaml
`Minimum value: 2
Maximum value: 9
`
Key Points
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/38
how to find number of vowels and consonant in string ?
To find the number of vowels and consonants in a string, you can loop through each character of the
string, check whether it is a vowel, consonant, or something else (like a space or special character), and
keep a count.
cpp
`#include <iostream>
#include <string>
using namespace std;
int main() {
string input;
int vowels = 0, consonants = 0;
// Check if it is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
// Check if it is a consonant (alphabet but not a vowel)
else if (ch >= 'a' && ch <= 'z') {
consonants++;
}
}
return 0;
}
`
Explanation
1. Input a String:
Use `getline(cin, input)` to read the whole string, including spaces.
2. Loop Through Each Character:
Use a range-based for loop (`for (char ch : input)`) to iterate through each character in the
string.
3. Convert to Lowercase:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/38
Convert the character to lowercase using `tolower(ch)` to handle case insensitivity.
4. Check Vowels:
Compare the character to `a`, `e`, `i`, `o`, and `u`. If it matches, increment the `vowels`
counter.
5. Check Consonants:
Check if the character is a letter (`ch >= 'a' && ch <= 'z'`) and not a vowel. If so, increment
the `consonants` counter.
6. Ignore Non-Alphabetic Characters:
Any character that is not a letter (e.g., numbers, spaces, punctuation) is ignored.
7. Output Results:
Print the total counts of vowels and consonants.
Example Run
Input:
csharp
Execution:
If you want to use a basic loop instead of a range-based for loop, here’s how you can rewrite the code:
cpp
`#include <iostream>
#include <string>
using namespace std;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/38
int main() {
string input;
int vowels = 0, consonants = 0;
// Check if it is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
}
// Check if it is a consonant (alphabet but not a vowel)
else if (ch >= 'a' && ch <= 'z') {
consonants++;
}
}
return 0;
}
`
Explanation of Changes
Example Run
Input:
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/38
Execution:
Output:
javascript
`Number of vowels: 3
Number of consonants: 7
`
To check if two strings are the same, you can compare their characters one by one. Here’s a simple code
example using a basic loop:
cpp
`#include <iostream>
#include <string>
using namespace std;
int main() {
string str1, str2;
bool areSame = true;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/38
for (int i = 0; i < str1.length(); i++) {
if (str1[i] != str2[i]) {
areSame = false; // If any character is different, set areSame to false
break; // Exit loop early since we know the strings are not the same
}
}
}
// Output result
if (areSame) {
cout << "The strings are the same." << endl;
} else {
cout << "The strings are not the same." << endl;
}
return 0;
}
`
Explanation
1. Input Strings:
Use `getline` to allow strings with spaces.
2. Check Lengths First:
If the lengths of the two strings are not equal, they cannot be the same.
In this case, we skip the character comparison.
3. Compare Character by Character:
Use a `for` loop to iterate through each character in the strings.
If any character in `str1` does not match the corresponding character in `str2`, set `areSame`
to `false` and break out of the loop.
4. Output the Result:
If `areSame` is `true`, the strings are identical.
Otherwise, they are different.
Example Run
Input:
csharp
Output:
sql
Input:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/38
csharp
Output:
sql
Key Notes
1. Case Sensitivity:
The comparison is case-sensitive. For example, `"Hello"` and `"hello"` are considered
different.
To make it case-insensitive, convert both strings to lowercase before comparison.
2. Edge Cases:
If both strings are empty, they are considered the same.
Strings with different lengths are immediately flagged as different.
If you don't want to use any inbuilt functions like `.length()` or direct character comparison methods,
you can manually calculate the lengths of the strings and compare their characters. Here's how to
achieve this:
cpp
`#include <iostream>
using namespace std;
int main() {
char str1[100], str2[100];
bool areSame = true;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/38
int len1 = 0, len2 = 0;
while (str1[len1] != '\0') {
len1++;
}
while (str2[len2] != '\0') {
len2++;
}
return 0;
}
`
Explanation
Example Run
Input:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/38
csharp
Output:
sql
Input:
csharp
Output:
sql
Key Points
Let me know if you'd like to extend this further, such as making it case-insensitive or optimizing the
code!
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/38