(C #) Reverses the string, reversing the word in a sentence.

Source: Internet
Author: User

This is a very basic interview question, but to be considerate.

First, reverse a string:

The basic idea is to change to a char array, then call the method inside C #, or set two index, traverse from head to tail, and swap.

Method One: Array.reverse (char *). Note that the string will be null or empty at the beginning.

         Public Static string ReverseString (string  input)        {            if  (String.IsNullOrEmpty (input))            {                 return input;             }             Char [] Chararray = input. ToCharArray ();            Array.reverse (Chararray);             return New String (Chararray);         }

Method two: Swap characters.

         Public Static stringReverseString1 (stringinput) {            if(String.IsNullOrEmpty (input)) {returninput; }            Char[] Chararray =input.            ToCharArray (); Chartmp;  for(inti =0, j = chararray.length-1;  I < J; i++, j--) {tmp=Chararray[i]; Chararray[i]=Chararray[j]; CHARARRAY[J]=tmp; }            return New string(Chararray); }

Reverse the words in a sentence:

         Public Static stringReversewords (stringinput) {            if(String.IsNullOrEmpty (input)) {returninput; }            string[] splits = input. Split (' '). Select (str=>Str. Trim ()).            ToArray (); StringBuilder Output=NewStringBuilder ();  for(inti = splits. Length-1; I >=0; i--) {output.                 Append (Splits[i]); if(I! =0) {output. Append (" "); }            }            returnoutput.         ToString (); }

(C #) Reverses the string, reversing the word in a sentence.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.