using strings in c code example

Example 1: string in c

#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
}

Example 2: how to create a string in c

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char greeting[] = "Hello";

Example 3: string in c

#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;
}

Example 4: c language string

//BY SAMEERAZ
#include<stdio.h>
#include<conio.h>
void main(){
char string[50];
clrscr();
printf("ENTER STRING:");
gets(s);//gets is basically used as scanf();
printf("TYPED STRING:%s",string);
getch();
}

Example 5: string in c

#include <stdio.h>

int main() {
  char *str1 = strdup("Hello");
  char *str2 = malloc(sizeof(char) * (strlen(str1) + 1));
  
  for (int i = 0; i < strlen(str1); ++i)
    str2[i] = str1[i];
  str2[strlen(str1)] = '\0'; // very important, the string stop to print
  printf("%s --> %s\n", str1, str2);
}

Tags:

C Example