khuang8493
6/15/2018 - 12:27 AM

Retreive each character in a string for C

Ways to deal with strings and the characters within the strings.

String and single Charactors within the string

If "s" is a string, we can use square brackets "[ ]" to represent the single characters within this string:

s[0] is the first character in this string

s[i] is the (i+1) character in this string

The lenghth of the string:

First we need to include the string library:

#include <string.h>

Then we can use a function called "strlen" to return the lenghth of the string as an integer:

int n = strlen(s);

To get each character of the inputed string:

for (int i=0; i<strlen(s); i++)

{

	printf("%c\n", s[i]);
	
}

A better way to write this piece of code, is to put the length of the string in an int, so that "strlen" don't have to run each time of the for loop:

for (int i=0, n=strlen(s); i<n; i<i++)

{

	printf("%c\n", s[i]);
	
}