年前秋招,代舍友笔试的一道题:
“输入字串,字串由单词和空格组成,将字串按单词倒序”
例如:
输入:hello world
输出:world hello
思路就是,先将整个字串倒序,再将字串按单词倒序打印。
代码如下:
#include <iostream>
using namespace std;
#define MAX_STRING_LENGTH 256
string strOrigin;
char strInverted[MAX_STRING_LENGTH];
void InvertedOrderByChar()//将字串逆序
{
int j = 0;
for (int i = strOrigin.length() - 1;i >=0;i--)
{
strInverted[j] = strOrigin[i];
j ++ ;
}
}
void InvertedOrderByWord()//将单词逆序打印
{
unsigned int i;
unsigned int j = 0;
int startIndex;
int endIndex;
int k;
for (i = 0;i < strlen(strInverted); i ++)
{
startIndex = i;
while(strInverted[j] != ' ' && j < strlen(strInverted) )
{
j ++;
}
endIndex = j -1;
for(k = endIndex;k >= startIndex; k--)
{
cout <<strInverted[k];
}
cout <<' ';
j = j + 1;
i = j - 1;
}
}
int main(int argc , char* argv[])
{
getline(cin,strOrigin);//输出数据
InvertedOrderByChar();
/*
for(unsigned int i = 0 ;i < strlen(strInverted);i ++)
{
cout << strInverted[i];
}
*/
//cout << endl;
InvertedOrderByWord();
}
最近项目用到C#,自学了一点C#发现其对于字串处理封装的类方法处理上述问题十分简单:
代码如下:
#region
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#endregion
namespace StrTest
{
class Program
{
static void Main(string[] args)
{
string myString = Console.ReadLine();
char separate = ' ';
string[] myWords;
myWords = myString.Split(separate);
for (int i = myWords.Length - 1; i >= 0; i --)
{
Console.Write(myWords[i]+" ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}