String Examples in C Programming

0
18

The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

#include <stdio.h>
    
int main()
    
{
        
char name[20];
        
printf("Enter name: ");
        
scanf("%s", name);
        
printf("Your name is %s.", name);
       
return 0;
    
}

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.

#include <stdio.h>
    
int main()
    
{
        
char name[30];
        
printf("Enter name: ");
        
fgets(name, sizeof(name), stdin);  // read string
        
printf("Name: ");
        
puts(name);    // display string
        
return 0;
    
}

Strings and Pointers

#include <stdio.h>
    
int main(void) 
    
{
      
char name[] = "Harry Potter";
      
printf("%c", *name);     // Output: H
      
printf("%c", *(name+1));   // Output: a
      
printf("%c", *(name+7));   // Output: o
      
char *namePtr;
      
namePtr = name;
      
printf("%c", *namePtr);     // Output: H
      
printf("%c", *(namePtr+1));   // Output: a
      
printf("%c", *(namePtr+7));   // Output: o
    
}

Strings can be passed to a function in a similar way as arrays.

#include <stdio.h>
    
void displayString(char str[]);
    
int main()
    
{
        
char str[50];
        
printf("Enter string: ");
        
fgets(str, sizeof(str), stdin);             
        
displayString(str);     // Passing string to a function.    
        
return 0;
    
}
    
void displayString(char str[])
    
{
        
printf("String Output: ");
        
puts(str);
    
}

Find the length of a string without using strlen() function.

#include <stdio.h>
int main()
{
        char s[1000];
        int i;
        printf("Enter a string: ");
        scanf("%s", s);
        for(i = 0; s[i] != '\0'; ++i);
        printf("Length of string: %d", i);
        return 0;
}

C Program to Copy String Without Using strcpy():

#include <stdio.h>
    
int main()
    
{
        
char s1[100], s2[100], i;
        
printf("Enter string s1: ");
        
fgets(s1, sizeof(s1), stdin);
        
for(i = 0; s1[i] != '\0'; ++i)
        
{
            
s2[i] = s1[i];
        
}
        
s2[i] = '\0';
        
printf("String s2: %s", s2);
        
return 0;
    
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here