Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 495
Jannis Höschele Avatar asked Jan 18 '16 08:01

Jannis Höschele


People also ask

How do you remove the first and last character?

To remove the first and last characters from a string, call the slice() method, passing it 1 and -1 as parameters, e.g. str. slice(1, -1) . The slice method returns a new string containing the extracted section from the original string. Copied!

How do I remove the starting and ending character from a string in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.


3 Answers

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])}";
like image 193
David Pilkington Avatar answered Oct 16 '22 17:10

David Pilkington


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())
like image 20
Hari Prasad Avatar answered Oct 16 '22 18:10

Hari Prasad


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.

like image 2
Mohit S Avatar answered Oct 16 '22 19:10

Mohit S