Jannis Höschele
Jannis Höschele

Reputation: 147

Delete the first char of a string and append to end of string

I need to get the first char of this string:

String s = "X-4711";

And put it after the number with an ';' , like: 4711;X.

I already tried it with:

String x = s.Split("-")[1] + ";" + s.Split("-")[0];

then I get it, but can I do it better or is this the only possible way?

Upvotes: 8

Views: 2121

Answers (3)

David Pilkington
David Pilkington

Reputation: 13618

var items = s.Split ("-");
string x = String.Format ("{0};{1}", items[1], items[0]);

At most this makes it a little more readable and a micro-optimisation of only having to split once.

EDIT :

As some of the comments have pointed out, if you are using C#6 you can make use of String Interpolation to format the string. It does the exact same thing, only looks a little better.

var items = s.Split ("-");
string x = $"{items[1]};{items[0])}";

Upvotes: 18

Hari Prasad
Hari Prasad

Reputation: 16986

Not sure what performance you are looking for small string operations, your code is well written and satisfy your needs.

One minor thing you might consider is removing additional split performed on input string.

var subs = s.Split ("-");
String.Format ("{0};{1}", subs [1], subs [0]);

If you are looking single liner (crazy programmer), this might help.

string.Join(";", s.Split('-').Reverse())

Upvotes: 4

Mohit S
Mohit S

Reputation: 14064

String.Substring: Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

string sub = input.Substring(0, 1);
string restStr = input.Substring(2, input.length-2);
// string restStr = input.Substring(2); Can also use this instead of above line
string madeStr = restStr + ";" + sub;

You call the Substring method to extract a substring from a string that begins at a specified character position and ends before the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and continues to the end of the string, call the Substring method.

Upvotes: 2

Related Questions