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?
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!
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.
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])}";
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())
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With