String Traversal implementation in C
Strings are a collection of characters followed by a ‘null’ character. ’Null’ is represented by ‘\0’. In C, string is considered as character array
Syntax:
To declare a string:
‘char string_name[];
To assign a value:
‘string_name[]’ = “value”;
‘value’ may be a string or set of characters as follows.
a[]= “Sample”;
a[15] = {‘S’,’a’,’m’,’p’,’l’,’e’,’\0’};
How to get the input and print the output?
There are some built-in functions to read and write the
string.
- ‘printf()’,’puts()’ -To print the output.
- ‘scanf()’,’gets()’- To get the input from the user.
- ‘fgets()’ – it is used to get the input from file.
Built-in functions to perform String operations:
- ‘strlen(string)’ – it gives you the length of the string.
- ‘strcpy(destination, source) – It Copies source data into destination.
- ‘strcat(dest, src)’ – it helps in concatenation of two strings.
- ‘strcmp(str1, str2)’ - it Compares two strings. It returns 0 if equal, otherwise it is 1.
- ‘strchr(str, ch)’ – it searches the first occurrence of character.
- ‘strstr(str, substr)’ – it gets you the substring.
Let us classify the Methods of String Traversal in C.
o
Using built-in functions
o
Using Pointers
Using Built-in functions:
C header
file <string.h> has variety of built-in functions related to string
listed already. Let us create a c
program to perform string traversal using strlen() function.
Program:
#include <stdio.h>
#include <string.h>
int main() {
char a_str[10];
printf("Enter
the String:\n");
scanf("%s",a_str);
// To find the
length
int n =
strlen(a_str);
printf("The
string entered character by character:\n");
for (int i = 0; i
<= n; i++) {
printf("%c\n", a_str[i]);
}
return 0;
}
Output:
Enter the String:
Goodday
The string entered character by character:
G
o
o
d
d
a
y
using Pointers:
This
program uses the pointer to access the string elements. Here, is the program.
Program:
#include <stdio.h>
int main() {
char a_str[10];
char *pt = a_str;
printf("Enter
the string:\n");
scanf("%s",&a_str);
printf("The
string is printed using Pointer\n");
while (*pt !=
'\0') {
printf("%c\n", *pt);
pt++;
}
return 0;
}
Output:
Enter the string:
Traversal
The string is printed using Pointer
T
r
a
v
e
r
s
a
l
Hope, these codes are useful to you. Keep Coding!!!
Comments
Post a Comment