Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在不改变C中特殊字符位置的情况下反转字符串数组#_C# - Fatal编程技术网

C# 如何在不改变C中特殊字符位置的情况下反转字符串数组#

C# 如何在不改变C中特殊字符位置的情况下反转字符串数组#,c#,C#,我正在做一个句子的倒装。我能做到。但我不确定,如何在不改变特殊字符位置的情况下反转单词。我正在使用正则表达式,但一旦它找到特殊字符,它就会停止单词的反转 代码如下: Console.WriteLine("Enter:"); string w = Console.ReadLine(); string rw = String.Empty; String[] arr = w.Split(' '); var regexItem = new Regex("^[a-zA-Z0-9]*$"); Stri

我正在做一个句子的倒装。我能做到。但我不确定,如何在不改变特殊字符位置的情况下反转单词。我正在使用正则表达式,但一旦它找到特殊字符,它就会停止单词的反转

代码如下:

Console.WriteLine("Enter:");
string w = Console.ReadLine();   
string rw = String.Empty;
String[] arr = w.Split(' ');
var regexItem = new Regex("^[a-zA-Z0-9]*$");
StringBuilder appendString = new StringBuilder();
for (int i = 0; i < arr.Length; i++)
{
    char[] chararray = arr[i].ToCharArray();
    for (int j = chararray.Length - 1; j >= 0; j--)
    {

     if (regexItem.IsMatch(rw))
{
    rw = appendString.Append(chararray[j]).ToString();
}
    }
    sb.Append(' ');
}              
Console.WriteLine(rw);
Console.ReadLine();
Console.WriteLine(“输入:”);
字符串w=Console.ReadLine();
string rw=string.Empty;
字符串[]arr=w.Split(“”);
var regexItem=新的正则表达式(“^[a-zA-Z0-9]*$”;
StringBuilder appendString=新的StringBuilder();
对于(int i=0;i=0;j--)
{
if(注册表项IsMatch(rw))
{
rw=appendString.Append(chararray[j]).ToString();
}
}
某人附加(“”);
}              
控制台.写入线(rw);
Console.ReadLine();
示例:输入

马歇尔!你好

预期产量

骆驼!奥利


以下是一个非正则表达式版本,可满足您的要求:

var sentence = "Hello, john!";
var parts = sentence.Split(' ');
var reversed = new StringBuilder();
var charPositions = sentence.Select((c, idx) => new { Char = c, Index = idx })
                            .Where(_ => !char.IsLetterOrDigit(_.Char));

for (int i = 0; i < parts.Length; i++)
{
     var chars = parts[i].ToCharArray();

     for (int j = chars.Length - 1; j >= 0; j--)
     {
         if (char.IsLetterOrDigit(chars[j]))
         {
            reversed.Append(chars[j]);
         }
     }
}

foreach (var ch in charPositions)
{
    reversed.Insert(ch.Index, ch.Char);
}

// olleH, nhoj!
Console.WriteLine(reversed.ToString());
var-station=“你好,约翰!”;
变量部分=句子分割(“”);
var reversed=新的StringBuilder();
var charPositions=句子。选择((c,idx)=>new{Char=c,Index=idx})
.Where(=>!char.isleterordigit(u.char));
对于(int i=0;i=0;j--)
{
if(char.isleterordigit(chars[j]))
{
反向追加(chars[j]);
}
}
}
foreach(charPositions中的var ch)
{
反向插入(ch.Index,ch.Char);
}
//奥利,nhoj!
Console.WriteLine(reversed.ToString());

基本上,诀窍是记住特殊字符(即非字母或数字)的位置,并将它们插入这些位置的末尾。

这里有一个非正则表达式版本,它可以满足您的需要:

var sentence = "Hello, john!";
var parts = sentence.Split(' ');
var reversed = new StringBuilder();
var charPositions = sentence.Select((c, idx) => new { Char = c, Index = idx })
                            .Where(_ => !char.IsLetterOrDigit(_.Char));

for (int i = 0; i < parts.Length; i++)
{
     var chars = parts[i].ToCharArray();

     for (int j = chars.Length - 1; j >= 0; j--)
     {
         if (char.IsLetterOrDigit(chars[j]))
         {
            reversed.Append(chars[j]);
         }
     }
}

foreach (var ch in charPositions)
{
    reversed.Insert(ch.Index, ch.Char);
}

// olleH, nhoj!
Console.WriteLine(reversed.ToString());
var句子=“你好,约翰!”;
变量部分=句子分割(“”);
var reversed=新建StringBuilder();
var charPositions=句子。选择((c,idx)=>new{Char=c,Index=idx})
.Where(=>!char.isleterordigit(u.char));
对于(int i=0;i=0;j--)
{
if(char.isleterordigit(chars[j]))
{
反向追加(chars[j]);
}
}
}
foreach(charPositions中的var ch)
{
反向插入(ch.Index,ch.Char);
}
//奥利,nhoj!
Console.WriteLine(reversed.ToString());

基本上,诀窍是记住特殊字符(即非字母或数字)的位置,并将它们插入这些位置的末尾。

正则表达式和LINQ的基本解决方案


没有LINQ的相同解决方案

publicstaticvoidmain()
{
控制台。WriteLine(“马歇尔!你好”);
控制台。书写线(反面(“马歇尔!你好”);
}
公共静态布尔或数字(字符串s)
{
foreach(s中的变量c)
{
if(!char.isleterordigit(c))
{
返回false;
}
}
返回true;
}
公共静态字符串反转(字符[]s)
{
阵列。反转(s);
返回新字符串;
}
公共静态字符串反转(字符串源)
{
变量部分=正则表达式拆分(来源,@“([^a-zA-Z0-9])”;
var results=新列表();
foreach(部分变量x)
{
结果。添加(个或多个数字(x)
?反向(x.ToCharArray())
:x);
}
返回字符串.Concat(结果);
}

使用正则表达式和LINQ的基本解决方案


没有LINQ的相同解决方案

publicstaticvoidmain()
{
控制台。WriteLine(“马歇尔!你好”);
控制台。书写线(反面(“马歇尔!你好”);
}
公共静态布尔或数字(字符串s)
{
foreach(s中的变量c)
{
if(!char.isleterordigit(c))
{
返回false;
}
}
返回true;
}
公共静态字符串反转(字符[]s)
{
阵列。反转(s);
返回新字符串;
}
公共静态字符串反转(字符串源)
{
变量部分=正则表达式拆分(来源,@“([^a-zA-Z0-9])”;
var results=新列表();
foreach(部分变量x)
{
结果。添加(个或多个数字(x)
?反向(x.ToCharArray())
:x);
}
返回字符串.Concat(结果);
}

这是一个没有LINQ的解决方案。我不确定什么是特殊角色

        string sentence = "Marshall! Hello.";
        List<string> words = sentence.Split(' ').ToList();
        List<string> reversedWords = new List<string>();

        foreach (string word in words)
        {
            char[] arr = new char[word.Length];

            for( int i=0; i<word.Length; i++)
            {
                if(!Char.IsLetterOrDigit((word[i])))
                {
                    for ( int x=0; x< i; x++)
                    {
                        arr[x] = arr[x + 1];
                    }
                    arr[i] = word[i];
                }
                else
                {
                    arr[word.Length - 1 - i] = word[i];
                }
            }

            reversedWords.Add(new string(arr));
        }

        string reversedSentence = string.Join(" ", reversedWords);

        Console.WriteLine(reversedSentence);

这是一个没有LINQ的解决方案。我不确定什么是特殊角色

        string sentence = "Marshall! Hello.";
        List<string> words = sentence.Split(' ').ToList();
        List<string> reversedWords = new List<string>();

        foreach (string word in words)
        {
            char[] arr = new char[word.Length];

            for( int i=0; i<word.Length; i++)
            {
                if(!Char.IsLetterOrDigit((word[i])))
                {
                    for ( int x=0; x< i; x++)
                    {
                        arr[x] = arr[x + 1];
                    }
                    arr[i] = word[i];
                }
                else
                {
                    arr[word.Length - 1 - i] = word[i];
                }
            }

            reversedWords.Add(new string(arr));
        }

        string reversedSentence = string.Join(" ", reversedWords);

        Console.WriteLine(reversedSentence);

此解决方案没有LINQ和正则表达式。这可能不是一个有效的答案,但对于较小的字符串值,它可以正常工作

    // This will reverse the string and special characters will just stay there.
    public string ReverseString(string rString)
    {
        StringBuilder ss = new StringBuilder(rString);
        int y = 0;
        // The idea is to swap values. Like swapping first value with last one. It will keep swapping unless it reaches at the middle of the string where no swapping will be needed.
        // This first loop is to detect first values.
        for(int i=rString.Length-1;i>=0;i--)
        {
            // This condition is to check if the values is String or not. If it is not string then it is considered as special character which will just stay there at same old position.
            if(Char.IsLetter(Convert.ToChar(rString.Substring(i,1))))
            {          
                // This is second loop which is starting from end to swap values from end with first.         
                for (int k = y; k < rString.Length; k++)
                {
                    // Again checking last values if values are string or not. 
                    if (Char.IsLetter(Convert.ToChar(rString.Substring(k, 1))))
                    {
                        // This is swapping. So st1 is First value in that string
                        // st2 is the last item in that string
                        char st1 = Convert.ToChar(rString.Substring(k, 1));
                        char st2 = Convert.ToChar(rString.Substring(i, 1));

                        //This is swapping. So last item will go to first position and first item will go to last position, To make sure string is reversed.
                        // Remember when the string value is Special Character, swapping will move forward without swapping.
                        ss[rString.IndexOf(rString.Substring(i, 1))] = st1;
                        ss[rString.IndexOf(rString.Substring(k, 1))] = st2;
                        y++;
                        // When the swapping is done for first 2 items. The loop will stop to change the values.
                        break;
                    }
                    else
                    {
                        // This is just increment if value was Special character. 
                        y++;
                    }
                }                    
            }
        }

        return ss.ToString();
    }
//这将反转字符串,特殊字符将留在那里。
公共字符串反向限制(字符串rString)
{
StringBuilder ss=新的StringBuilder(rString);
int y=0;
//其思想是交换值。就像交换第一个值和最后一个值一样。它将继续交换,除非它到达字符串中间不需要交换的位置。
//第一个循环用于检测第一个值。
对于(int i=rString.Length-1;i>=0;i--)
{
//此条件用于检查值是否为字符串。如果它不是字符串,则它被视为特殊字符,将保持在原来的位置。
if(Char.isleter(Convert.ToChar(rString.Substring(i,1)))
{          
//这是第二个循环,它从一端开始,将值从一端交换到第一个。
for(int k=y;k    // This will reverse the string and special characters will just stay there.
    public string ReverseString(string rString)
    {
        StringBuilder ss = new StringBuilder(rString);
        int y = 0;
        // The idea is to swap values. Like swapping first value with last one. It will keep swapping unless it reaches at the middle of the string where no swapping will be needed.
        // This first loop is to detect first values.
        for(int i=rString.Length-1;i>=0;i--)
        {
            // This condition is to check if the values is String or not. If it is not string then it is considered as special character which will just stay there at same old position.
            if(Char.IsLetter(Convert.ToChar(rString.Substring(i,1))))
            {          
                // This is second loop which is starting from end to swap values from end with first.         
                for (int k = y; k < rString.Length; k++)
                {
                    // Again checking last values if values are string or not. 
                    if (Char.IsLetter(Convert.ToChar(rString.Substring(k, 1))))
                    {
                        // This is swapping. So st1 is First value in that string
                        // st2 is the last item in that string
                        char st1 = Convert.ToChar(rString.Substring(k, 1));
                        char st2 = Convert.ToChar(rString.Substring(i, 1));

                        //This is swapping. So last item will go to first position and first item will go to last position, To make sure string is reversed.
                        // Remember when the string value is Special Character, swapping will move forward without swapping.
                        ss[rString.IndexOf(rString.Substring(i, 1))] = st1;
                        ss[rString.IndexOf(rString.Substring(k, 1))] = st2;
                        y++;
                        // When the swapping is done for first 2 items. The loop will stop to change the values.
                        break;
                    }
                    else
                    {
                        // This is just increment if value was Special character. 
                        y++;
                    }
                }                    
            }
        }

        return ss.ToString();
    }