在C语言中,实现字符串逆序的技巧主要包括以下几点:
#include<stdio.h>
#include<string.h>
void reverse_string(char *str) {
int len = strlen(str);
char temp;
for (int i = 0, j = len - 1; i < j; i++, j--) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
#include<stdio.h>
#include<string.h>
void reverse_substring(char *start, char *end) {
if (start >= end) {
return;
}
char temp = *start;
*start = *end;
*end = temp;
reverse_substring(start + 1, end - 1);
}
void reverse_string(char *str) {
int len = strlen(str);
reverse_substring(str, str + len - 1);
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
typedef struct Stack {
int top;
unsigned capacity;
char *array;
} Stack;
Stack *create_stack(unsigned capacity) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (char *)malloc(stack->capacity * sizeof(char));
return stack;
}
int is_full(Stack *stack) {
return stack->top == stack->capacity - 1;
}
int is_empty(Stack *stack) {
return stack->top == -1;
}
void push(Stack *stack, char item) {
if (is_full(stack)) {
return;
}
stack->array[++stack->top] = item;
}
char pop(Stack *stack) {
if (is_empty(stack)) {
return '\0';
}
return stack->array[stack->top--];
}
void reverse_string(char *str) {
int len = strlen(str);
Stack *stack = create_stack(len);
for (int i = 0; i < len; i++) {
push(stack, str[i]);
}
for (int i = 0; i < len; i++) {
str[i] = pop(stack);
}
}
int main() {
char str[] = "Hello, World!";
printf("Original string: %s\n", str);
reverse_string(str);
printf("Reversed string: %s\n", str);
return 0;
}
这些技巧都可以实现字符串逆序,你可以根据自己的需求和喜好选择合适的方法。