5.12 LAB: Iterating through a C string without using strlen The program in Figure 4.3.1 demonstrates Iterating through a
Posted: Sun May 15, 2022 1:44 pm
5.12 LAB: Iterating through a C string without using
strlen
The program in Figure 4.3.1 demonstrates Iterating through a C
string using strlen. A call for strlen is used in a
for loop:
Since the length of the string does not change within the loop,
we can slightly improve this code fragment by
calling strlen before the loop:
However, this change is not really necessary since most
compilers are designed to transform our code by making it faster
and consume less resources (code
optimization).
Your task is to rewrite this program without
calling strlen.
given code:
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_LENGTH = 16;
int main() {
char userName[MAX_LENGTH]; // = "Alan Turing";
int i;
cout << "Input string: ";
cin.getline(userName, MAX_LENGTH, '\n');
cout << "Before: [" << userName <<
"]" << endl;
//for (i = 0; i < strlen(userName); ++i)
{
for (i = 0; /* Write your code here */ ; ++i) {
if (userName == ' ') {
userName = '_';
}
}
cout << "After: [" << userName
<< "]" << endl;
return 0;
}
strlen
The program in Figure 4.3.1 demonstrates Iterating through a C
string using strlen. A call for strlen is used in a
for loop:
Since the length of the string does not change within the loop,
we can slightly improve this code fragment by
calling strlen before the loop:
However, this change is not really necessary since most
compilers are designed to transform our code by making it faster
and consume less resources (code
optimization).
Your task is to rewrite this program without
calling strlen.
given code:
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_LENGTH = 16;
int main() {
char userName[MAX_LENGTH]; // = "Alan Turing";
int i;
cout << "Input string: ";
cin.getline(userName, MAX_LENGTH, '\n');
cout << "Before: [" << userName <<
"]" << endl;
//for (i = 0; i < strlen(userName); ++i)
{
for (i = 0; /* Write your code here */ ; ++i) {
if (userName == ' ') {
userName = '_';
}
}
cout << "After: [" << userName
<< "]" << endl;
return 0;
}