【問題】c語言 字串反序...


Recommended Posts

c語言 字串反序...

要怎麼在不知字串有多長的情形下寫這個程式阿?

#include <stdio.h>

#include <stdlib.h>

void reverse(char str[]);

int main(void)

{

char str[5];

gets(str);

reverse(str);

system("pause");

return 0;

}

void reverse(char str[])

{

int i,j,temp;

for(i=1;i<5;i++)

for(j=0;j<(5-i);j++)

{

temp=str[j];

str[j]=str[j+1];

str[j+1]=temp;

}

puts(str);

}

整個程式執行起來就是怪怪的....

麻煩大大幫我一下

感激不盡~~~

不好意思.....寫出來了......

鏈接文章
分享到其他網站

#include <string.h>

size_t strlen(const char *s);

strlen()這個函式可以傳回字串長度:


char s[]="test";
printf("%d\n",strlen(s));

反轉字串另外一個比較方便的作法是直接用STL的reverse() 下面是C++的code


#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
int main(void){
char s[]="abcde";
reverse(s,s+strlen(s));
cout<<s<<endl;
system("pause");
return 0;
}

鏈接文章
分享到其他網站
  • 2 weeks later...
  • 2 weeks later...
  • 2 months later...

請登入後來留意見

在登入之後,您才能留意見



立即登入