Changing an "." to an "_" in a C# string - c#

I'm developing a piece of software in C# and the end result is an Excel spreadsheet. The title of the spreadsheet is created using several variables to explain exactly what the spreadsheet is. One of the variables is a string which contains data like this:
'1.1.1'
I need to convert it at the point of creating the spreadsheet to be:
'1_1_1'
I have tried using the String.Replace method but it just seems to ignore it. Any ideas?
Best Regards

I bet you doing this:
myString.Replace(".","_");
When you should be doing this:
myString = myString.Replace(".","_");
Remember, in .Net strings are immutable, so any changes result in a new string.

Chances are you're ignoring the result of string.Replace. You need:
text = text.Replace('.', '_');
Just calling Replace doesn't change the existing string - it creates a new string and returns it. Strings are immutable in .NET - they never change after creation.

When you use string.Replace are you remembering that you have to assign it?
yourString.Replace(".", "_");
Will do nothing.
string newString = yourString.Replace(".", "_");
will return the string with the dots replaced with underscores.

If I had to guess, you're not capturing the value returned by String.Replace. Strings are immutable, so String.Replace returns a new string, which you need to store a reference to.
string foo = "1.1.1";
foo = foo.Replace('.', '_');

String input = "1.1.1";
input = input.Replace(".", "_");

strings are immutable, so make sure you're using it like this:
string myString = "1.1.1";
myString = myString.Replace('.', '_');

String.Replace is the right way to do this:
private void button1_Click(object sender, RoutedEventArgs e) {
String myNumbers = "1.1.1";
Console.WriteLine("after replace: " + myNumbers);
myNumbers = myNumbers.Replace(".", "_");
Console.WriteLine("after replace: " + myNumbers);
}
will produce:
after replace: 1.1.1
after replace: 1_1_1

Related

c# Replace backslash in string

I am reading the contents of an XLS file. Some older versions of excel add what I assume are escape sequences within the cell that causes me problems upon attempting to create a SQL column of that name.
Example string I have to work with is passed as
\0\0K\0\b\0Job
I would like to return this string as "Job". None of the replace sequences in the following job make a change and it returns as
\0\0K\0\b\0Job
C# does not allow that string to be created manually without escaping it with "\\", which defeats the purpose of what I need.
Any suggestions?
public static string CleanupHeaders(string _Col)
{
// Replace your #"\" parameter with double-escaped: #"\\"
_Col = _Col.Replace(#"\\0K", "");
_Col = _Col.Replace(#"\\b", "");
_Col = _Col.Replace(#"\\0", "");
return _Col;
}
Any suggestions?
I have one, since the string comes in as "\0\0K\0\b\0Job" your string replace methods _Col.Replace shouldn't need to use the literal syntax. In C# the \ is an escape character and the following characters create an escape sequence.
The issue is the verbatim string with the # syntax. Remove that and you get "Job". See this working .NET Fiddle - it has several demonstrations that will easily show you what happens. Take a look # MSDN's reference on string literals for more details.
public static string CleanupHeaders(string _Col)
{
_Col = _Col.Replace("\0K", "");
_Col = _Col.Replace("\b", "");
_Col = _Col.Replace("\0", "");
return _Col;
}
There should be no reason to use them in this situation.
Updated
The OP altered the question a little, so here's an update .NET Fiddle.
It's possible that the thing that's reporting the content of the string to you is reporting actual zero characters as \0 for human readability.
Try removing the #s from your replacement strings there.
The code that you provided should be working exactly as expected as seen in this example.
It's All In How It's Called
Since you mentioned that your initial string isn't being changed, it's worth noting that your replace function actually returns a string and doesn't perform an inline replacement, so you'll need to call it through :
// This will set your original string to the result of your CleanupHeaders() method
yourColumnVariable = CleanupHeaders(yourColumnVariable);
If you do want to perform an inline replacement of your existing string, simply update your CleanupHeaders() method to use a ref parameter to perform an update to the actual reference that was passed in :
// Notice the ref keyword
public static void CleanupHeaders(ref string _Col)
{
_Col = _Col.Replace(#"\0K", "");
_Col = _Col.Replace(#"\b", "");
_Col = _Col.Replace(#"\0", "");
}
and then you could simply call it using :
// This will update the yourColumnVariable to reflect any changes made in the method
CleanupHeaders(ref yourColumnVariable);
You can see an updated example that uses the ref approach here.
If you have a debugger, I would first of all suggest seeing what value the _Col string is when it's passed into your CleanupHeaders() method.
Depending where the string:
"\0\0K\0\b\0Job"
came from; I would imagine it is already escaped when it reaches your code.
The string would look something like this: "\\0\\0K\\0\\b\\0Job" when it reaches your method.
I would suggest 1 of 2 things:
1: Replace all your \ in the string with - or any character of your choice:
_Col = _Col.Replace(#"\\", "-");
And then replace your matching strings that now have the - prefix:
// Replace all your escaped backslashes
_Col = _Col.Replace(#"\\", "-");
// Now replace your new prefix + values you are looking to replace
_Col = _Col.Replace("-0K", "");
_Col = _Col.Replace("-0", "");
_Col = _Col.Replace("-b", "");
return _Col;
Or
2: \0 Is recognised as a character as it's escaped; so it's not being printed/output. Try changing your .Replace(#"\0", ""); with .Replace(#"\\0", ""); like so:
public static string CleanupHeaders(string _Col)
{
_Col = _Col.Replace(#"\\0K", ""); // Replaces the exact already escaped \\ value.
_Col = _Col.Replace(#"\\b", "");
_Col = _Col.Replace(#"\\0", "");
return _Col;
}

Whats the opposite operation for += using strings?

For example I have a
String a="Hello";
a+="World";
this would put World at the end. How can I put it at the beginning?
Simply:
string a = "Hello";
a = "World" + a;
Ultimately, a += "World"; is just abbreviated syntax for:
a = a + "World";
No such abbreviation exists if you want to reverse the order of the operands.
As a side note - keep in mind that if you are doing this a lot (in a loop etc) it may be better to consider StringBuilder to avoid lots of intermediary strings.
You can also call the Insert function;
a = a.Insert(0, "start");
To prepend, you'd simply use.
a = "World" + a;
Please bear in mind that actually, you'd be creating a completely new string, you can't pre or postpend any string in C# as they are immutable. Consider using String.Format or StringBuilder.AppendFormat if you have special string processing needs.
Just do this:
String a = "Hello";
a = "World " + a;
Just use
string a = "Hello";
a = "World" + a;
Because a+= "World"; is equavalent with;
a = a + "World";
Check out for more information How to: Concatenate Multiple Strings (C# Programming Guide)
Hint: This is not in this case but if performance is important, you should always use the StringBuilder class to concatenate strings. It represents mutable strings.
it's simple you can add the new word in the begin
String a="Hello";
a="World" + a;
You can't do that with any special operator. You will have to do:
a = "World"+a;
Use StringBuilder to perform string operations.
http://msdn.microsoft.com/en-us/library/2839d5h5(v=vs.71).aspx

How to select only the characters after a repeated symbol in a long string

If i am using C# and i have a string coming in from a database like this:
\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
And i only want this part of the string:
1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML
How can i get this string if there is more than one "\" symbol?
You can use the LastIndexOf() method of the String class:
string s = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
Console.Out.WriteLine(s.Substring(s.LastIndexOf('\\') + 1));
Hope, this helps.
Use String.Split to split string by parts and then get the last part.
Using LINQ Enumerable.Last() :
text.Split('\\').Last();
or
// todo: add null-empty checks, etcs
var parts = text.Split('\\');
strign lastPart = parts[parts.Length - 1];
You can use a combination of String.LastIndexOf("\") and String.Substring(lastIndex+1). You could also use (only in the sample you provided) Path.GetFileName(theString).
string[] x= line.Split('\');
string goal =x[x.Length-1];
but linq will be easier
You can use regex or split the string by "\" symbol and take the last element of array
using System.Linq;
public class Class1
{
public Class1()
{
string s =
#"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA54E7CF517B2863E.XML";
var array = s.Split('\\');
string value = array.Last();
}
}
newstring = string.Substring(string.LastIndexOf(#"\")+1);
It seems like original string is like filePath.
This could be one easy solution.
string file = #"\RBsDC\1031\2011\12\40\1031-215338-5DRH44PUEM2J51GRL7KNCIPV3N-META-ENG-22876500BBDE449FA.xml";
string name = System.IO.Path.GetFileName(file);

string.replace is not working

I have function which accepts string (which is basically a XML doc). I am making this change:
if (filterXml.Contains("&"))
{
filterXml.Replace("&", "&");
}
It is hitting this condition but not replacing the
& to &
What is wrong here?
Remember, strings are immutable. So you have to assign the return value of the Replace method (notice that it returns a String object) back to your variable.
if (filterXml.Contains("&"))
{
filterXml = filterXml.Replace("&", "&");
}
If you're doing a lot of work with String objects, make sure to read the the String reference page
You need to save the result:
filterXml = filterXml.Replace("&", "&");
but I would recommend encoding ALL special XML characters.
You don't even need to do the Contains check. Just do the following:
filterXml = filterXml.Replace("&", "&");
If there aren't any ampersands in the string, then nothing will change.
Try -
if (filterXml.Contains("&"))
{
filterXml = filterXml.Replace("&", "&");
}
Strings are immutable in .net, so the replace function returns a new string rather than altering the string it is called on. You are able to assign the altered result to the variable that contained your original string value.
if (filterXml.Contains("&"))
{
filterXml = filterXml.Replace("&", "&");
}

string.Replace (or other string modification) not working

For the following code, I can't get the string.Replace to work:
someTestString.Replace(someID.ToString(), sessionID);
when I debug and check parameters they have values I expect - i.e. someID.ToString() got "1087163075", and sessionID has "108716308" and someTestString contains "1087163075".
I have no idea why this would not work change someTestString
Complete sample:
string someTestString =
"<a href='myfoldert/108716305-1.jpg' target='_blank'>108716305-1.jpg</a>"
someTestString.Replace("108716305", "NewId42");
the result (in someTestString) should be this:
"<a href='myfoldert/NewId42-1.jpg' target='_blank'>NewId42-1.jpg</a>"
but it doesn't change. The string for someTestString remains unchanged after hitting my code.
Strings are immutable. The result of string.Replace is a new string with the replaced value.
You can either store result in new variable:
var newString = someTestString.Replace(someID.ToString(), sessionID);
or just reassign to original variable if you just want observe "string updated" behavior:
someTestString = someTestString.Replace(someID.ToString(), sessionID);
Note that this applies to all other string functions like Remove, Insert, trim and substring variants - all of them return new string as original string can't be modified.
someTestString = someTestString.Replace(someID.ToString(), sessionID);
that should work for you
strings are immutable, the replace will return a new string so you need something like
string newstring = someTestString.Replace(someID.ToString(), sessionID);
You can achieve the desired effect by using
someTestString = someTestString.Replace(someID.ToString(), sessionID);
As womp said, strings are immutable, which means their values cannot be changed without changing the entire object.

Categories

Resources