string str = "Student_123_";
I need to replace the last character "_" with ",". I did it like this.
str.Remove(str.Length -1, 1);
str = str + ",";
However, is it possible to achieve it more efficiently. may be one line of code.??
BTW, last character can be any character. So Replace wont work here.
No.
In C# strings are immutable and thus you can not change the string "in-place". You must first remove a part of the string and then create a new string. In fact, this is also means your original code is wrong, since str.Remove(str.Length -1, 1); doesn't change str at all, it returns a new string! This should do:
str = str.Remove(str.Length -1, 1) + ",";
C# .NET makes it almost too easy.
str = str.TrimEnd('_')
Elegant but not very efficient.
Replaces any character at the end of str with a comma.
str = Regex.Replace(str, ".$", ",");
That's a limitation of working with string. You can use StringBuilder if you need to do a lot of changes like this. But it's not worth it for the simple task you need.
str = str.Substring(0, str.Length - 1) + ",";
Use the StringBuilder class
StringBuilder mbuilder = new StringBuilder("Student_123_");
mbuilder[mbuilder.Length-1] = ',';
Console.WriteLine(mbuilder.ToString());
str = str.Substring(0, str.Length-1) + ",";
Well, what you have won't work because str.Remove(...) doesn't manipulate str, it returns a new string with the removal operation completed on it.
So - you need:
str = str.Remove(str.Length-1,1);
str = str + ",";
In terms of efficiency, there are several other choices you could make (substring, trim ...) but ultimately you're going to get the same time/space complexity.
EDIT:
Also, don't try to squash everything into one line, the programmers who come after you will appreciate the greater readability. (Although in this case a single line is just as easy to read.) One line != more efficient.
With one line of code you could write:
str = str.Remove(str.Length - 1, 1) + ",";
str.Remove doesn't modify str, it returns a new string. Your first line should read str = str.Remove...
One line? OK: str = str.Remove(str.Length - 1) + ",";
I think that's as efficient as you're going to get. Technically, you are creating two new strings here, not one (The result of the Remove, and the result of the Concatenation). However, everything I can think of to not create two strings, ends up creating more than 1 other object to do so. You could use a StringBuilder, but that's heavier weight than an extra string, or perhaps a char[], but it's still an extra object, no better than what I have listed above.
//You mean like this? :D
string str = "Student_123_";
str = $"{str.Remove(str.Length -1)},";
Related
Let's say I have a foreach-loop with strings like this:
String newStr='';
String str='a b c d e';
foreach(String strChar in str.split(' ')) {
newStr+=strChar+',';
}
the result would be something like: a,b,c,d,e, but what I want is a,b,c,d,e without the last comma. I normally split the last comma out but this seems ugly and overweight. Is there any lightweight way to do this?
Additional to this question: Is there any easy solution to add an "and" to the constellation that the result is something like: a, b, c, d and e for user output?
p.s.: I know that I can use the replace-method in the example but this is not what I'm looking because in most cases you can't use it (for example when you build a sql string).
I would use string.Join:
string newStr = string.Join(",", str.Split(' '));
Alternatively, you could add the separator at the start of the body of the loop, but not on the first time round.
I'd suggest using StringBuilder if you want to keep doing this by hand though. In fact, with a StringBuilder you could just unconditionally append the separator, and then decrement the length at the end to trim that end.
You also wrote:
for example when you build a sql string
It's very rarely a good idea to build a SQL string like this. In particular, you should absolutely not use strings from user input here - use parameterized SQL instead. Building SQL is typically the domain of ORM code... in which case it's usually better to use an existing ORM than to roll your own :)
you're characterizing the problem as appending a comma after every string except the last. Consider characterizing it as prepending a comma before every string but the first. It's an easier problem.
As for your harder version there are several dozen solutions on my blog and in this question.
Eric Lippert's challenge "comma-quibbling", best answer?
string.Join may be your friend:
String str='a b c d e';
var newStr = string.Join(",", str.Split(' '));
Here's how you can do it where you have "and" before the last value.
var vals = str.Split(' ');
var ans = vals.Length == 1 ?
str :
string.Join(", ", vals.Take(vals.Length - 1))) + ", and " + vals.Last();
newStr = String.Join(",", str.split(' '));
You can use Regex and replace whitespaces with commas
string newst = Regex.Replace(input, " ", ",");
First, you should be using a StringBuilder for string manipulations of this sort. Second, it's just an if conditional on the insert.
System.Text.StringBuilder newStr = new System.Text.StringBuilder("");
string oldStr = "a b c d e";
foreach(string c in oldStr.Split(' ')) {
if (newStr.Length > 0) newStr.Append(",");
newStr.Append(c);
}
INPUT : There's string that numbers, and a string, dots and spaces. Notice that e defines a the separator between the numbers.
e.27.3.90.. .e 3.50 2.30..e2.0.1.2. .50..
OUTPUT : I want to remove all the spaces and those extra dots except for the one that makes up following and add a , before e,
,e273.90,e3502.30,e2012.50
Best catch was this How to remove extra decimal points?. But it's based on Javascript parseFloat().
I also saw this post : Convert to valid decimal data type. But that's in terms of SQL and pretty much using multiple replace().
PS: There are so many posts regarding regex in various kind. I tried to build one, but seems like no success so far.
Please propose any efficient one shot regex or ideas.
Would like to hear the performance gain/loss of this regex vs multiple replace()
Here is the code I have been gasping ;)..:
List<string> myList;
string s = "";
string s2 = "";
string str = "e.27.3.90..bl% .e 3.50 2.30. #rp.e2.0.1.2..50..y*x";
s = Regex.Replace(str, #"\b[a-df-z',\s]+", "");
myList = new List<string>(Regex.Split(s, #"[e]"));
Last str is your result
string str = "e.27.3.90..bl% .e 3.50 2.30. #rp.e2.0.1.2..50..y*x";
str = Regex.Replace(str, "[^e^0-9]", "");
str = Regex.Replace(str, "([0-9]{2}?)(e|$)", ".$1,$2");
//str = "," + str.Substring(0, str.Length - 1);
Remove all dots from the string.
Split the string into separate items at each "e".
For each item, add a dot before the last 2 digits.
Recombine the items back into one string, placing a comma between items.
These steps are easily performed with the standard String methods, but you could use regexes if you want.
I know nothing of C# so I'm hoping somebody here can help. So my question is how would I add a "," after the fourth character in a string. Something like:
Hell,o?
You can use .Insert():
string test = "Hello";
test = test.Insert(4, ",");
You should check if the string is long enough though like so:
if (test.Length > 4) {
test = test.Insert(4, ",");
}
You need to use String.Insert and give the number 4 as parameter (since the first char is on place 0)
string s = "hello";
s = s.Insert(4, ",");
Use String.Insert.
E.g. myString.Insert(4, ",");
String.Insert is the answer:
string test1 = "Hello";
string test2 = test1.Insert(4, ",");
http://msdn.microsoft.com/en-us/library/system.string.insert.aspx
var str ="Hello";
var finalString = string.Format("{0},{1}",str.Substring(0,4),str.Substring(4));
Firstly, strings are immutable so you have to create a new string
var sampleString = "Testing";
var resultString = sampleString.Insert(3, ",);
resultString is "Test,ing"
Use below code
String str = "Hello";
str = str.Substring(0, 4) + "," + str.Substring(4, str.Length - 4);
I'm gonna Propose an alternative to insert, this way it'll be possible for future users to use for editing a longer string and put in values at different intervals eg.
"hello my name is Anders"
becomes
"hell,o my, nam,e is, And,ers"
A string in C# is basically an array of chars, so you could loop through it and when you reach the fourth loop you could insert your ,
something like this
string hello="hello";
string newvar ="";
foreach(int i =0;i<hello.length;i++)
{
if(i==4)
newvar+=",";
newvar+=hello[i];
}
if you want it to be each fourth space you can check if 0%=4/i
you can also use Substring split it up into multiple pieces put in your "," and put it back together, I suggest you take a look at the documentation for the string class at Microsofts homepage
How to ignore the first 10 characters of a string?
Input:
str = "hello world!";
Output:
d!
str = str.Remove(0,10);
Removes the first 10 characters
or
str = str.Substring(10);
Creates a substring starting at the 11th character to the end of the string.
For your purposes they should work identically.
str = "hello world!";
str.Substring(10, str.Length-10)
you will need to perform the length checks else this would throw an error
Substring is probably what you want, as others pointed out. But just to add another option to the mix...
string result = string.Join(string.Empty, str.Skip(10));
You dont even need to check the length on this! :) If its less than 10 chars, you get an empty string.
Substring has two Overloading methods:
public string Substring(int startIndex);//The substring starts at a specified character position and continues to the end of the string.
public string Substring(int startIndex, int length);//The substring starts at a specified character position and taking length no of character from the startIndex.
So for this scenario, you may use the first method like this below:
var str = "hello world!";
str = str.Substring(10);
Here the output is:
d!
If you may apply defensive coding by checking its length.
The Substring has a parameter called startIndex. Set it according to the index you want to start at.
You Can Remove Char using below Line ,
:- First check That String has enough char to remove ,like
string temp="Hello Stack overflow";
if(temp.Length>10)
{
string textIWant = temp.Remove(0, 10);
}
Starting from C# 8, you simply can use Range Operator. It's the more efficient and better way to handle such cases.
string AnString = "Hello World!";
AnString = AnString[10..];
Use substring method.
string s = "hello world";
s=s.Substring(10, s.Length-10);
You can use the method Substring method that takes a single parameter, which is the index to start from.
In my code below i deal with the case were the length is less than your desired start index and when the length is zero.
string s = "hello world!";
s = s.Substring(Math.Max(0, Math.Min(10, s.Length - 1)));
For:
var str = "hello world!";
To get the resulting string without the first 10 characters and an empty string if the string is less or equal in length to 10 you can use:
var result = str.Length <= 10 ? "" : str.Substring(10);
or
var result = str.Length <= 10 ? "" : str.Remove(0, 10);
First variant being preferred since it needs only one method parameter.
There is no need to specify the length into the Substring method.
Therefore:
string s = hello world;
string p = s.Substring(3);
p will be:
"lo world".
The only exception you need to cater for is ArgumentOutOfRangeException if
startIndex is less than zero or greater than the length of this instance.
Calling SubString() allocates a new string. For optimal performance, you should avoid that extra allocation. Starting with C# 7.2 you can take advantage of the Span pattern.
When targeting .NET Framework, include the System.Memory NuGet package. For .NET Core projects this works out of the box.
static void Main(string[] args)
{
var str = "hello world!";
var span = str.AsSpan(10); // No allocation!
// Outputs: d!
foreach (var c in span)
{
Console.Write(c);
}
Console.WriteLine();
}
I have a string of type
ishan,training
I want to split the string after "," i.e i want the output as
training
NOTE: "," does not have a fixed index as the string value before "," is different at different times.
e.g ishant,marcela OR ishu,ponda OR amnarayan,mapusa etc...
From all the above strings i just need the part after ","
You can use String.Split:
string[] tokens = str.Split(',');
string last = tokens[tokens.Length - 1]
Or, a little simpler:
string last = str.Substring(str.LastIndexOf(',') + 1);
var arr = string.Split(",");
var result = arr[arr.length-1];
sourcestring.Substring(sourcestring.IndexOf(',')). You might want to check sourcestring.IndexOf(',') for -1 for strings without ,.
I know this question has already been answered, but you can use linq:
string str = "1,2,3,4,5";
str.Split(',').LastOrDefault();
Although there are several comments mentioning the issue of multiple commas being found, there doesn't seem to be any mention of the solution for that:
string input = "1,2,3,4,5";
if (input.IndexOf(',') > 0)
{
string afterFirstComma = input.Split(new char[] { ',' }, 2)[1];
}
This will make afterFirstComma equal to "2,3,4,5"
Use String.Split(",") assign the result in to a string array and use what you want.
Heres a VB version. I'm sure its easy to translate to C# though
Dim str as string = "ishan,training"
str = str.split(",")(1)
return str