Write a program to reverse a string without using theandfunctions defined in the string.h library.
时间: 2024-03-17 17:43:28 浏览: 53
Sure, here's a program written in C to reverse a string without using any predefined functions from string.h library:
```
#include<stdio.h>
void reverseString(char str[]);
int main()
{
char str[100];
printf("Enter a string: ");
scanf("%s", str);
reverseString(str);
printf("Reversed string is: %s", str);
return 0;
}
void reverseString(char str[])
{
int length = 0;
// Calculate the length of the string
while (str[length] != '\0')
{
length++;
}
// Swap characters from beginning and end
for (int i = 0; i < length / 2; i++)
{
char temp = str[i];
str[i] = str[length - i - 1];
str[length - i - 1] = temp;
}
}
```
In this program, we first take input from the user and pass it to the `reverseString()` function. Inside this function, we calculate the length of the string by iterating through it till we find the null character `'\0'`. Then, we swap the first character with the last one, second with second last one, and so on till we reach the middle of the string. Finally, we print the reversed string.
阅读全文