Interview Preparation Exam  >  Interview Preparation Notes  >  Placement Papers - Technical & HR Questions  >  Strings (Part - 2), C Programming Interview Questions

Strings (Part - 2), C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation PDF Download

4. How can I right-justify a string?

Even though the C language does not provide a standard function that right-justifies a string, you can easily build your own function to perform this action. Using the rtrim() function, you can create your own function to take a string and right-justify it. Here is how this task is accomplished:

 

#include <stdio.h>
#include <string.h>
#include <malloc.h>
void main(void);
char* rjust(char*);
char* rtrim(char*);
void main(void)
{
     char* rjust_str = "This string is not right-justified.                  ";
     /* Show the status of the string before calling the rjust()
        function. */
     printf("Before calling rjust(), rjust_str is '%s'\n.", rjust_str);
     /* Call the rjust() function to right-justify this string. */
     rjust(rjust_str);
     /* Show the status of the string
        after calling the rjust() function. */
     printf("After calling rjust(), rjust_str is '%s'\n.", rjust_str);
}
/* The rjust() function right-justifies a string. */
char* rjust(char* str)
{
     int n = strlen(str);   /* Save the original length of the string. */
     char* dup_str;
     dup_str = strdup(str);  /* Make an exact duplicate of the string. */
     rtrim(dup_str);         /* Trim off the trailing spaces. */
     /* Call sprintf() to do a virtual "printf" back into the original
        string. By passing sprintf() the length of the original string,
        we force the output to be the same size as the original, and by
        default the sprintf() right-justifies the output. The sprintf()
        function fills the beginning of the string with spaces to make
        it the same size as the original string. */
     sprintf(str, "%*.*s", n, n, dup_str);
     free(dup_str);    /* Free the memory taken by
                          the duplicated string. */
     return str;       /* Return a pointer to the string. */
}
/* The rtrim() function removes trailing spaces from a string. */
char* rtrim(char* str)
{
     int n = strlen(str) - 1;  /* Start at the character BEFORE the null
                                  character (\0). */
     while (n>0)            /* Make sure we don't go out of bounds... */
     {
          if (*(str+n) != ' ')    /* If we find a nonspace character: */
          {
               *(str+n+1) = '\0'; /* Put the null character at one
                                     character past our current
                                     position. */
               break;             /* Break out of the loop. */
          }
          else      /* Otherwise, keep moving backward in the string. */
               n--;
     }
     return str;                   /* Return a pointer to the string. */
}

 

The rjust() function first saves the length of the original string in a variable named n. This step is needed because the output string must be the same length as the input string. Next, the rjust() function calls the standard C library function named strdup() to create a duplicate of the original string. A duplicate of the string is required because the original version of the string is going to be overwritten with a right-justified version. After the duplicate string is created, a call to the rtrim() function is invoked (using the duplicate string, not the original), which eliminates all trailing spaces from the duplicate string.

Next, the standard C library function sprintf() is called to rewrite the new string to its original place in memory. The sprintf() function is passed the original length of the string (stored in n), thereby forcing the output string to be the same length as the original. Because sprintf() by default right-justifies string output, the output string is filled with leading spaces to make it the same size as the original string. This has the effect of right-justifying the input string. Finally, because the strdup() function dynamically allocates memory, the free() function is called to free up the memory taken by the duplicate string.


5. How can I pad a string to a known length?

Padding strings to a fixed length can be handy when you are printing fixed-length data such as tables or spreadsheets. You can easily perform this task using the printf() function. The following example program shows how to accomplish this task:

 

#include <stdio.h>
char *data[25] = {
     "REGION", "--Q1--",    "--Q2--",   "--Q3--", "  --Q4--",
     "North", "10090.50", "12200.10", "26653.12", "62634.32",
     "South", "21662.37", "95843.23", "23788.23", "48279.28",
     "East", "23889.38", "23789.05", "89432.84", "29874.48",
     "West", "85933.82", "74373.23", "78457.23", "28799.84" };
void main(void);
void main(void)
{
     int x;
     for (x=0; x<25; x++)
     {
          if ((x % 5) == 0 && (x != 0))
               printf("\n");
          printf("%-10.10s", data[x]);
     }
}

 

In this example, a character array (char* data[]) is filled with this year's sales data for four regions. Of course, you would want to print this data in an orderly fashion, not just print one figure after the other with no formatting. This being the case, the following statement is used to print the data:

printf("%-10.10s", data[x]);

The "%-10.10s" argument tells the printf() function that you are printing a string and you want to force it to be 10 characters long. By default, the string is right-justified, but by including the minus sign (-) before the first 10, you tell the printf() function to left-justify your string. This action forces the printf() function to pad the string with spaces to make it 10 characters long. The result is a clean, formatted spreadsheet-like

output:

 

REGION      --Q1--   --Q2--     --Q3--    --Q4--
North      10090.50  12200.10  26653.12  62634.32
South      21662.37  95843.23  23788.23  48279.28
East       23889.38  23789.05  89432.84  29874.48
West       85933.82  74373.23  78457.23  28799.84


6. How can I copy just a portion of a string?

You can use the standard C library function strncpy() to copy one portion of a string into another string. The strncpy() function takes three arguments: the first argument is the destination string, the second argument is the source string, and the third argument is an integer representing the number of characters you want to copy from the source string to the destination string. For example, consider the following program, which uses the strncpy() function to copy portions of one string to another:

 

#include <stdio.h>
#include <string.h>
void main(void);
void main(void)
{
     char* source_str = "THIS IS THE SOURCE STRING";
     char dest_str1[40] = {0}, dest_str2[40] = {0};
     /* Use strncpy() to copy only the first 11 characters. */
     strncpy(dest_str1, source_str, 11);
     printf("How about that! dest_str1 is now: '%s'!!!\n", dest_str1);
     /* Now, use strncpy() to copy only the last 13 characters. */
     strncpy(dest_str2, source_str + (strlen(source_str) - 13), 13);
     printf("Whoa! dest_str2 is now: '%s'!!!\n", dest_str2);
}

 

The first call to strncpy() in this example program copies the first 11 characters of the source string intodest_str1. This example is fairly straightforward, one you might use often. The second call is a bit more complicated and deserves some explanation. In the second argument to the strncpy() function call, the total length of the source_str string is calculated (using the strlen() function). Then, 13 (the number of characters you want to print) is subtracted from the total length of source_str. This gives the number of remaining characters in source_str. This number is then added to the address of source_str to give a pointer to an address in the source string that is 13 characters from the end of source_str.

Then, for the last argument, the number 13 is specified to denote that 13 characters are to be copied out of the string. The combination of these three arguments in the second call to strncpy() sets dest_str2 equal to the last 13 characters of source_str.

The example program prints the following output:

 

How about that! dest_str1 is now: 'THIS IS THE'!!!
Whoa! dest_str2 is now: 'SOURCE STRING'!!!

 

Notice that before source_str was copied to dest_str1 and dest_st2dest_str1 and dest_str2 had to be initialized to null characters (\0). This is because the strncpy() function does not automatically append a null character to the string you are copying to. Therefore, you must ensure that you have put the null character after the string you have copied, or else you might wind up with garbage being printed.

 

 

The document Strings (Part - 2), C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation is a part of the Interview Preparation Course Placement Papers - Technical & HR Questions.
All you need of Interview Preparation at this link: Interview Preparation
85 docs|57 tests

Top Courses for Interview Preparation

85 docs|57 tests
Download as PDF
Explore Courses for Interview Preparation exam

Top Courses for Interview Preparation

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation

,

MCQs

,

Strings (Part - 2)

,

ppt

,

Summary

,

Strings (Part - 2)

,

mock tests for examination

,

Strings (Part - 2)

,

Free

,

video lectures

,

pdf

,

Extra Questions

,

shortcuts and tricks

,

Important questions

,

C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation

,

study material

,

Semester Notes

,

C Programming Interview Questions | Placement Papers - Technical & HR Questions - Interview Preparation

,

Sample Paper

,

practice quizzes

,

Previous Year Questions with Solutions

,

Objective type Questions

,

Viva Questions

,

past year papers

,

Exam

;