面試經典題目:字串翻轉I am a student
阿新 • • 發佈:2019-02-06
- 只有比別人更早、更勤奮地努力,才能嚐到成功的滋味
題目:寫一個函式,將字串翻轉,翻轉方式如下:“I am a student”反轉成“student a am I”,不借助任何庫函式
,要求單詞內字元的順序不變,句子中單詞以空格符隔開。
思路:先反轉整個字串,然後再反轉字串。譬如先將“I am a student”反轉為“tneduts a ma I”,然後再對每個字串(空格分割)反轉一次。
程式碼(c++):
#include<iostream> #include<string> #include <algorithm> using namespace std; int main() { string str; while(getline(cin,str)) { int len = str.length(); reverse(str.begin(),str.end()); int from = 0; int i=0; int to; while(i<len) //之前此處寫得是while(str[i]),會有陣列越界的可能 { if(str[i]!=' ') { from = i; while(i<len&&str[i]!=' ') { i++; } to = i; reverse(str.begin()+from,str.begin()+to);//這句一定要放在if內部,之前做一個筆試題目,老是出錯,後來才發現是這裡的問題 } i++; } cout<<str<<endl; } return 0; }
程式碼(c):
結果:#include <stdio.h> #include <stdlib.h> void ReverseString(char *s,int from,int to) { char t; while(from<to) { t=s[from]; s[from++]=s[to]; s[to--]=t; } } int main() { char str[100]; int l,i,from,to; printf("Enter a String: "); gets(str); l=strlen(str); ReverseString(str,0,l-1); printf("\n總體翻轉:%s\n",str); i=0; while(str[i]) { if(str[i]!=' ') { from=i; while(str[i]&&str[i]!=' ') { i++; } i=i-1; to=i; } char t; while(from<to) { t=str[from]; str[from++]=str[to]; str[to--]=t; } i++; } printf("\nString:%s\n",str); return 0; }