C#实现字符串单词逆序输出
问题: 给定一个字符串。对字符串的单词进行逆序输出
例如:
input String: This is a test
output String: test a is This
input String: !dog is smart.
output String: smart. is dog!
初步简单略欠缺的方式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lianxi
{
class Program
{
static void Main(string[] args)
{
int i;
string s1=Console.ReadLine();
//利用 ToCharArray()函数将字符串变成字符数组
char[] s=s1.ToCharArray();
//然后利用 for循环将字符数组倒序输出
for(i=s1.Length-1;i>=0;i--)
{
Console.Write("{0}",s[i]);
}
Console.Readkey();
}
}
}
或者
using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lianxi
{
class Program
{
static void Main(string[] args)
{
string s1=Console.ReadLine();
int i;
//定义一个新的字符串数组,将用户输入的字符串从空格处分离开
string[] s=s1.Split(' ');
//用 for循环语句倒序输出字符串数组
for(i=s.Length-1;i>=0;i--)
{
//在每个字符串中间加个空格
console.Write(s[i]+' ');
}
Console.Readkey();
}
}
}
网上查找大神们用的复杂一些的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSDN考试
{
class Program
{
public static void Main()
{
string str_0 = Console.ReadLine().Trim();
string str = str_0;
Program sol = new Program();
List<string> result = sol.solution(str);
for (int i = 0; i < result.Count; i++)
{
Console.Write(result[i] + " ");
}
Console.ReadKey();
}
/// <summary>
/// 判定参数str是否为标点符号
/// </summary>
/// <param name="str"></param>
/// <returns>
/// 若是标点符号,返回true,否则返回false
/// </returns>
public static Boolean isPunctuation(String str)
{
String[] punctuations = { ",", ".", "?", "!" };
int l = punctuations.Length;
for (int i = 0; i < l; i++)
{
if (str == punctuations[i])
{
return true;
}
}
return false;
}
public List<string> solution(string str)
{
List<string> result = new List<string>();
// TODO: 请在此编写代码
int strLen = str.Length;
int j = strLen - 1;
int wordLength = 0;
for (int i = strLen - 1; i > -1; i--)
{
//i为0且i指向的字符不为标点与空格时
if (i == 0 && !isPunctuation(str.Substring(i, 1)) && (str.Substring(i, 1) != ""))
{
//计算单词的长度
wordLength = j - i + 1;
//输出单词
result.Add(str.Substring(i, wordLength));
}
else if (isPunctuation(str.Substring(i, 1)) || str.Substring(i, 1) == " ")
{
//计算单词的长度,可能为0
wordLength = j - i;
//输出单词
result.Add(str.Substring(i + 1, wordLength));
//输出标点符号或空格
result.Add(str.Substring(i, 1));
//将j更新为i-1指向未输出的最末尾字符
j = i - 1;
}
}
return result;
}
}
}