Click here to Skip to main content
15,918,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi, there

In one of my interview; interviewer asked to write a program for following

Q :

There is a TextBox which having this predefined value as "Val1!@#$%Val2!@#$%Val3!@#$Val4!@#$%" in it.

On a button click they want to reverse this text in a label as follow.

Output : Val4!@#$%Val3!@#$%Val2!@#$%Val1!@#$%


How to do this?

N.B. Text don't having any space. They all are joined. So split function not working for this

ASP.NET
<asp:TextBox ID="txt1" Text="Val1!@#$%Val2!@#$%Val3!@#$%Val4" runat="server" 
            Width="280px">Val1!@#$%Val2!@#$%Val3!@#$%Val4</asp:TextBox>
        </br>
        <asp:Button ID="btnResult" Text="GetResult" runat="server" 
            onclick="btnResult_Click" />
        </br>
        <asp:Label ID="result" runat="server"></asp:Label>
Posted
Comments
PIEBALDconsult 27-Dec-15 0:50am    
Regular Expressions.
[no name] 27-Dec-15 1:05am    
Input : Val1!@#$%Val2!@#$%Val3!@#$Val4!@#$%
Output : Val4!@#$%Val3!@#$%Val2!@#$%Val1!@#$%

In above input and output string "%" is missing in input. Make sure that you are providing correct one.

1 solution

You can "split" a string into a string[] using any arbitrary string(s) as the criterion:
C#
string[] spliton = new string[]{"!@#$%"};
string test = @"Val1!@#$%Val2!@#$%Val3!@#$%Val4";

// in some method or EventHandler
// requires Linq
IEnumerable<string> splitAry = this.test.Split(spliton, StringSplitOptions.RemoveEmptyEntries).Reverse();

StringBuilder sb = new StringBuilder();

foreach (string str in splitAry)
{
    sb.Append(str);
    sb.Append(spliton[0]);
}

string final = sb.ToString();
If you want to use Linq a bit more to make this shorter:
C#
private List<string> ReverseAndAppend(string source, string appendelement)
{
    return source
        .Split(new string[]{appendelement}, StringSplitOptions.RemoveEmptyEntries)
        .Reverse()
        .Select(str => string.Concat(str, appendelement)).ToList();
}

// test like this:

// string test = @"Val1!@#$%Val2!@#$%Val3!@#$%Val4";
// List<string> testList = ReverseAndAppend(test, @"!@#$%");
 
Share this answer
 
v3
Comments
PIEBALDconsult 27-Dec-15 15:24pm    
One of the main problems with Split is that it doesn't return the delimiters it splits on.
Split has very limited utility.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900