1. Question

Found this code on one of the topic. would u mind to explain what actually the code do

Code:
```string Change_me(string my_string)
{

for(int i = 0; i <my_string.length(); i++)
{
if(isdigit(my_string[i])!=0)
{
if(isdigit(my_string[i+1])==0)
{
my_string.insert(i+1, "v");
//v is just an arbitary choice
//it could be any other letter
//but it has to be a LETTER

}
}
}
//Changed -7*-7 case
for ( i = 0; i <my_string.length(); i++)
{
if(my_string[i]=='-')
{
if((my_string[i-1]!='v')&&(my_string[i-1]!=')'))
{
my_string.replace(i,1,"y");
}
}
}

return my_string;
}```

2. Originally Posted by isarapearl
Found this code on one of the topic. would u mind to explain what actually the code do
What does it do? Demonstrates an attempt to access memory outside the valid range of the string object that's what:
Code:
```for(int i = 0; i <my_string.length(); i++)
{
if(isdigit(my_string[i ])!=0)
{
if(isdigit(my_string[i+1])==0)
{
my_string.insert(i+1, "v");
//v is just an arbitary choice
//it could be any other letter
//but it has to be a LETTER
}
}
}```
What happens if the length of the string is 10 (valid indicies between 0 and 9 inclusive) and i is 9? The second call to isdigit attempts to access my_string[10]... which is bad.

Code:
```for ( i = 0; i <my_string.length(); i++)
{
if(my_string[i ]=='-')
{
if((my_string[i-1]!='v')&&(my_string[i-1]!=')'))
{
my_string.replace(i,1,"y");
}
}
}```
What happens when i is 0? Tell me what is my_string[-1] equal to?

Popular pages Recent additions