实例:
I am a student, and a good boy.
.boy good a and, student a am I
JAVA实现如下:
import java.util.Scanner;
public class ReverseText {
public static boolean isAlpha(char tp){
if((tp>='A'&&tp<='Z')||(tp>='a'&&tp<='z'))
return true;
return false;
}
public static void main(String [] ages){
System.out.println("请输入文本:");
Scanner sc =new Scanner(System.in);
String text;
text = sc.nextLine();
String splitx[]=text.split(" ");
int n =splitx.length;
for(int i = 0;i<n;i++){
if(isAlpha(splitx[i].charAt(splitx[i].length()-1)))
if(i==n-1) continue;
else splitx[i] = " " +splitx[i];
else{
StringBuilder sb = new StringBuilder(splitx[i]);
char temp = splitx[i].charAt(splitx[i].length()-1);
for(int j = splitx[i].length()-2 ;j>=0;j--){
sb.replace(j+1, j+2,""+(splitx[i].charAt(j)) );
// System.out.println(sb.toString());
}
sb.replace(0, 1,""+temp );
if(i==n-1) {
splitx[i] =""+sb.toString();
}
else {
splitx[i] =" "+sb.toString();
}
}
}
for(int j =n-1;j>=0;j--){
System.out.print(splitx[j]);
}
}
}
C++实现如下:
#include <iostream>
#include<string>
#include<vector>
using namespace std;
bool isAlpha(char op){
if((op>='A' and op<='Z') ||(op>='a' and op<='z'))
return true;
else
return false;
}
int main() {
string str,temp;
vector<string> text;
cout<<"请输入文本:"<<endl;
cin.ignore();
while(getline(cin,str)){
for(int i =0, cp = 0; i<str.length() ;i++){
if(str[i]==' '){
temp = str.substr(cp,i+1);
if(!isAlpha(temp[temp.length()-1])){
char tag = temp[temp.length()-1];
for(int j =temp.length()-2;j>=1;j--)
temp[j] = temp[j-1];
temp[0]=tag;
}//if
text.push_back(" "+temp);
cp=i+1;
} //if
}//for
}//while
for(int i=text.size()-1;i>=0;i--){
cout<<text[i];
}
return 1;
}