题目:
翻转单词。将字符串按单词翻转,如here you are 翻转成are you here
一、利用strtok(字符数组分割函数),和reverse函数:
1、C++代码:
#include<iostream>
#include<algorithm>
#include <cstring>
using namespace std;
string wordReverse(string src)
{
string ans;
//temp:用于临时存放分割后的结果
//tempStr:为使用reverse函数,将char指针引导的字符数组,转化为字符串
char* temp;
string tempStr;
//为使用strtok函数,创建src对应的字符数组
char srcC[src.length()];
//翻转src字符串后,存入字符数组srcC
reverse(src.begin(),src.end());
strcpy(srcC,src.data());
//分割依据
const char* basis=" ";
//初次分割
temp=strtok(srcC,basis);
while(temp)
{
//进行逐个翻转
tempStr=temp;
reverse(tempStr.begin(),tempStr.end());
//赋值给最后的结果
ans=ans+tempStr+" ";
temp=strtok(NULL,basis);
}
return ans;
}
int main()
{
string str="here you are";
cout<<wordReverse(str);
return 0;
}
2、结果:
二、JAVA代码:
public class WordReverse {
public static void main(String[] args) {
System.out.println(reverse("where you are"));
}
// 首先将整个字符串按照字符翻转,再找到每个单词,将单词翻转
static String reverse(String src){
String s1 = reverseString(src);
// 切割单词
String[]words = s1.split("\\s");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
sb.append(reverseString(words[i])+ " ");
}
return sb.deleteCharAt(sb.length()-1).toString();
}
public static String reverseString(String iniString){
// StringBuilder sBuilder = new StringBuilder(iniString) // 和StringBuffer效果差不多。
StringBuffer sBuffer = new StringBuffer(iniString);
return sBuffer.reverse().toString();
}
}
参考:https://www.cnblogs.com/xiaoyh/p/10304381.html