Copyright © tutorialspoint.com

Latest C Tutorial

C - Play with Strings

previous next


Advertisements

  • In C language Strings are defined as an array of characters or a pointer to a portion of memory containing ASCII characters. A string in C is a sequence of zero or more characters followed by a NULL '\0' character:

  • It is important to preserve the NULL terminating character as it is how C defines and manages variable length strings. All the C standard library functions require this for successful operation.

  • All the string handling functions are prototyped in: string.h or stdio.h standard header file. So while using any string related function, don't forget to include either stdio.h or string.h. May be your compiler differes so please check before going ahead.

  • If you were to have an array of characters WITHOUT the null character as the last element, you'd have an ordinary character array, rather than a string constant.

  • String constants have double quote marks around them, and can be assigned to char pointers as shown below. Alternatively, you can assign a string constant to a char array - either with no size specified, or you can specify a size, but don't forget to leave a space for the null character!

char *string_1 = "Hello";
char string_2[] = "Hello";
char string_3[6] = "Hello";

Reading and Writing Strings:

One possible way to read in a string is by using scanf. However, the problem with this, is that if you were to enter a string which contains one or more spaces, scanf would finish reading when it reaches a space, or if return is pressed. As a result, the string would get cut off. So we could use the gets function

A gets takes just one argument - a char pointer, or the name of a char array, but don't forget to declare the array / pointer variable first! What's more, is that it automatically prints out a newline character, making the output a little neater.

A puts function is similar to gets function in the way that it takes one argument - a char pointer. This also automatically adds a newline character after printing out the string. Sometimes this can be a disadvantage, so printf could be used instead.

#include <stdio.h>

int main() {
  char array1[50];
  char *array2;

  printf("Now enter another string less than 50");
  printf(" characters with spaces: \n");
  gets(array1);

  printf("\nYou entered: ");
  puts(array1);

  printf("\nTry entering a string less than 50");
  printf(" characters, with spaces: \n");
  scanf("%s", array2);

  printf("\nYou entered: %s\n", array2);

  return 0;
}

This will produce following result:

Now enter another string less than 50 characters with spaces:
hello world

You entered: hello world

Try entering a string less than 50 characters, with spaces:
hello world

You entered: hello 

String Manipulation Functions


previous next

Copyright © tutorialspoint.com