Practice questions on Strings in C++

C++Server Side ProgrammingProgramming

String is an important part of programming. Strings are the array of character types. In competitive exams like GATE also it is an important topic. So let’s discuss some key points about string and then we will proceed to some questions that will help you clear your concepts about string.

String in a programming language can be stored in two different ways. They are using character array (char str[size]) and using a pointer that will point to the string (char * ch = “Hello”). There are some important things related to the use of the character array and pointer to a string. They are

  • To find the size of string we need to pass character array instance of string to sizeof method i.e. sizeof(str).
  • The end of a string is marked by the null character i.e. ‘\0’.
  • There is a method to find the length of string known as strlen().
  • To modify string i.e. changing characters of the string, char array is used whereas accessing the single character of the string is not possible using a pointer.

Let’s see some practice questions

Predict the output of the

Example

char name[] = "TutorialsPoint";
char *ptr = name;
cout<<++ptr;

Output

utorialsPoint

The value of pointer is increased by one so it will start printing from index 1.

char name[] = "TutorialsPoint";
int length = strlen(name);
for(int i=length;i>1;i--)
   printf("%c", name[i]);

Output

tniopslairot

Printing reverse of the string by starting from length to 1.

char c[] = "LearnProgrammingAtTutorialsPoint";
char *p =c;
printf("%s", p + c[1] - c[2]+1) ;

Output

ProgrammingAtTutorialsPoint

Here we have created a pointer to the string and there increase the values of the pointer by some index which print the rest of the string.

raja
Published on 04-Feb-2020 07:45:27
Advertisements