2017-10-05 95 views
3

我试图让下面的代码工作,所以如果反向在阵列中的所有单词,而不第一个

输入是:如何你是花花公子?

输出应该是:

如何时代uoy edud?

我认为我很接近完成它,但我不明白为什么,正则表达式不起作用它不被识别。 下面是REPL:https://repl.it/MHzu/1

using System.Collections.Generic; 
using System.Linq; 
using System; 
using System.Text.RegularExpressions; 

public class Kata 
{  
    static void Main(string[] args) 
    { 
      string str = Console.ReadLine();    
      string opaa = str; 
      Match m = Regex.match(str,"(\w*) (\w.*)"); 
      string hoho = m.Groups[1]; 
      string strrev = ""; 
      foreach (var word in opaa.Split(' ')) 
      { 
       string temp = " "; 
       foreach (var ch in word.ToCharArray()) 
       { 
       temp = ch + temp; 
       } 
       strrev = strrev + temp + ""; 
      } 
      Console.WriteLine(hohoo + strrev); 
    } 
} 
+2

为什么你需要一个正则表达式? –

+0

因为我想得到第一个词,那么我就是这样做,如果你有更好的解决方案,分享它。 – Asparuh

+0

分而治之:如果你有一个string []的解决方案,你可以分成字符串[0]和字符串[1..n],求解第二个数组并重新加入。 – Fildor

回答

5

您可以使用LINQ太

string input = "think that I am very close to finish"; 

var output = string.Join(" ",input.Split() 
            .Select((x, i) => i == 0 ? x : string.Concat(x.Reverse()))); 
+0

谢谢你,你的解决方案非常棒! – Asparuh

+2

对不起,但是* *例子*'你怎么样?'是一个*计数器的例子*:预计'如何时代uoy edud?实际'如何时代uoy?edud'(请注意问号'?') –

2

我为了提取和反向话只建议Regex.Replace

string src = "How are you dude?"; 

    // Side effect, which we usually should avoid 
    int index = -1; 

    // \p{L}+ - all Unicode letters 
    string result = Regex.Replace(src, @"\p{L}+", match => ++index == 0 
     ? match.Value 
     : string.Concat(match.Value.Reverse())); 

    Console.WriteLine(result); 

结果:

How era uoy edud? 

请注意,非字母符号(比如标点符号)为保留;对于给定的

srec = "Punctuations: comma, semicolon are in use!"; 

结果将是

Punctuations: ammoc, nolocimes era ni esu! 
相关问题