Hi, I am

Ngô Tôn

I am a programmer.

Home / Programming / C/C++ / Đảo các kí tự của chuỗi

Đảo các kí tự của chuỗi

Yêu cầu: Đảo các kí tự của 1 chuỗi

Thuật toán: dùng biến tạm lưu chuỗi được đảo ngược

Code:

/************************Invert string******************/
#include "stdio.h"
#include "conio.h"
#include "stdlib.h" // thu vien ham malloc()
#include "string.h" // thu vien ham memset()

#define MAX_LENGTH 100

char* InvertString(char *str);

void main()
{
char str[MAX_LENGTH];
printf("\nNhap chuoi khong qua 100 ki tu: ");
fflush(stdin);
gets(str);
printf("\nChuoi dao nguoc: %s", InvertString(str));
getch();
}
// Ham dao cac ki tu trong chuoi
char* InvertString(char *str)
{
char *pTemp;
int length = strlen(str);
int i = 0;
pTemp = (char*)malloc(length + 1);
if(pTemp == NULL)
{
printf("\nError in memory");
return NULL;
}
memset(pTemp, NULL, length + 1); // assign pTemp = NULL
while(i < length)
{
*(pTemp + i) = *(str + length - 1 - i);
i++;
}
*(pTemp + i) = '\0';

return pTemp;
}

Kết quả:

About ngoton

Ngô Tôn is a programmer with passion for tailored software solutions. Comes with 7+ years of IT experience, to execute beautiful front-end experiences with secure and robust back-end solutions.

Check Also

Xây dựng hàm bạn để tính diện tích hình chữ nhật

Yêu cầu: Xây dựng hàm bạn để tính diện tích hình chữ nhật Code: Giải …

Leave a Reply

avatar
  Subscribe  
Notify of