String: replace last ".something" in a string? - c#

I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?

string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new

ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new

You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)

string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;

No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"

Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}

Related

looking for best way for string manipulation

I m looking for for some best way for string manipulation. Below is the expacted output,
[System/EventID=100 or System/EventID=108], commutative string should starts with [ and end with ] plus has to remove extra or in between?
try
{
string systemEvents = string.Empty;
var eventIds = "100,108".Split(',');
systemEvents += "[";
foreach (var eventId in eventIds)
{
systemEvents += "System/EventID=" + eventId + " or ";
}
var X = systemEvents.Remove(systemEvents.Length - 4).Trim();
var Y = X + "]";
}
catch (Exception ex)
{
throw ex;
}
You can make use of available string handling functions like String.Format()(which replace specified format items with the text representation of the corresponding object values.) and String.Join()(Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string.) to do this work. Try the following snippet, also Check a Working Example Here
string eventIdStr = String.Join(" or ", eventIds.Select(x=> "System/EventID=" +x))
string systemEvents = String.Format("[{0}]",eventIdStr);
var s = string.Format("[{0}]", string.Join(" or ", "100,108".Split(',').Select(x=> "System/EventID=" + x));

Regex catch string between strings

I created a small function to catch a string between strings.
public static string[] _StringBetween(string sString, string sStart, string sEnd)
{
if (sStart == "" && sEnd == "")
{
return null;
}
string sPattern = sStart + "(.*?)" + sEnd;
MatchCollection rgx = Regex.Matches(sString, sPattern);
if (rgx.Count < 1)
{
return null;
}
string[] matches = new string[rgx.Count];
for (int i = 0; i < matches.Length; i++)
{
matches[i] = rgx[i].ToString();
//MessageBox.Show(matches[i]);
}
return matches;
}
However if i call my function like this: _StringBetween("[18][20][3][5][500][60]", "[", "]");
It will fail. A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd;
However i can not because i dont know if the character is going to be a bracket or a word.
Sorry if this is a stupid question but i couldn't find something similar searching.
A way would be if i changed this line string sPattern = "\\" + sStart + "(.*?)" + "\\" + sEnd; However i can not because i don't know if the character is going to be a bracket or a word.
You can escape all meta-characters by calling Regex.Escape:
string sPattern = Regex.Escape(sStart) + "(.*?)" + Regex.Escape(sEnd);
This would cause the content of sStart and sEnd to be interpreted literally.

If statement based on StartsWith not finding "\\" in C#

I have a string called fileNameArrayEdited which contains "\\windows".The below if statement is not running.
Thinking the problem is else where as people have given me code that should work will be back once I found the problem... thanks!
if (fileNameArrayEdited.StartsWith("\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
// Put all file names in root directory into array.
string[] fileNameArray = Directory.GetFiles(#specifiedDir);
int specifiedDirCount = specifiedDir.Count();
string fileNameArrayEdited = specifiedDir.Remove(0, specifiedDirCount);
Console.WriteLine(specifiedDir.Remove(0, specifiedDirCount));
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
Console.ReadLine();
Use '#' at the beginning of your string if you are searching for exactly two slash
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
They are called verbatim strings and they are ignoring escape characters.For better explanation you can take a look at here: http://msdn.microsoft.com/en-us/library/362314fe.aspx
But I suspect in here your one slash is escape character
"\\windows"
So you must search for one slash like this:
if (fileNameArrayEdited.StartsWith(#"\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
When we write
string s1 = "\\" ;
// actual value stored in s1 is "\"
string s2 = #"\\" ;
// actual value stored in s2 is "\\"
The second type of string(s) are called "verbatim" strings.

How to trim/replace a char '\' or '"' from a string?

I need to use a string for path for a file but sometimes there are forbidden characters in this string and I must replace them. For example, my string _title is rumbaton jonathan \"racko\" contreras.
Well I should replace the chars \ and ".
I tried this but it doesn't work:
_title.Replace(#"/", "");
_title.Replace(#"\", "");
_title.Replace(#"*", "");
_title.Replace(#"?", "");
_title.Replace(#"<", "");
_title.Replace(#">", "");
_title.Replace(#"|", "");
Since strings are immutable, the Replace method returns a new string, it doesn't modify the instance you are calling it on. So try this:
_title = _title
.Replace(#"/", "")
.Replace(#"""", "")
.Replace(#"*", "")
.Replace(#"?", "")
.Replace(#"<", "")
.Replace(#">", "")
.Replace(#"|", "");
Also if you want to replace " make sure you have properly escaped it.
Try regex
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");
Before: "M"\a/ry/ h**ad:>> a/:?"| litt|le|| la"mb.?
After: Mary had a little lamb.
Also another answer from same post is much cleaner
private static string CleanFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
from How to remove illegal characters from path and filenames?
Or you could try this (probably terribly inefficient) method:
string inputString = #"File ~!##$%^&*()_+|`1234567890-=\[];',./{}:""<>? name";
var badchars = Path.GetInvalidFileNameChars();
foreach (var c in badchars)
inputString = inputString.Replace(c.ToString(), "");
The result will be:
File ~!##$%^&()_+`1234567890-=[];',.{} name
But feel free to add more chars to the badchars before running the foreach loop on them.
See http://msdn.microsoft.com/cs-cz/library/fk49wtc1.aspx:
Returns a string that is equivalent to the current string except that all instances of oldValue are replaced with newValue.
I have written a method to do the exact operation that you want and with much cleaner code.
The method
public static string Delete(this string target, string samples) {
if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(samples))
return target;
var tar = target.ToCharArray();
const char deletechar = '♣'; //a char that most likely never to be used in the input
for (var i = 0; i < tar.Length; i++) {
for (var j = 0; j < samples.Length; j++) {
if (tar[i] == samples[j]) {
tar[i] = deletechar;
break;
}
}
}
return tar.ConvertToString().Replace(deletechar.ToString(CultureInfo.InvariantCulture), string.Empty);
}
Sample
var input = "rumbaton jonathan \"racko\" contreras";
var cleaned = input.Delete("\"\\/*?><|");
Will result in:
rumbaton jonathan racko contreras
Ok ! I've solved my issue thanks to all your indications. This is my correction :
string newFileName = _artist + " - " + _title;
char[] invalidFileChars = Path.GetInvalidFileNameChars();
char[] invalidPathChars = Path.GetInvalidPathChars();
foreach (char invalidChar in invalidFileChars)
{
newFileName = newFileName.Replace(invalidChar.ToString(), string.Empty);
}
foreach (char invalidChar in invalidPathChars)
{
newFilePath = newFilePath.Replace(invalidChar.ToString(), string.Empty);
}
Thank you so musch everybody :)

How to Replace the String in C#?

I have the string string test="http://www.test.com//web?testid=12".
I need to replace with in the string // into /.
Problem is if I use string a=test.replace("//","/") I get http:/www.test.com/web?testid=12 all with single slash(/) but I need http://www.test.com/web?testid=12.
I need only the second // nearby web, not first // near by www.
How to do this?
You can make second replace
string test="http://www.test.com//web?testid=12";
string a=test.Replace("//","/").Replace("http:/","http://");
=)
string test = #"http://www.test.com//web?testid=12";
test = test.Substring(0, test.LastIndexOf(#"//") - 1)
+ test.Substring(test.LastIndexOf(#"//")).Replace(#"//", #"/");
Or since its a Uri, you can do:
Uri uri = new Uri(test);
string newTest = uri.Scheme + #"//" + uri.Authority
+ uri.PathAndQuery.Replace(#"//",#"/");
string test="http://www.test.com//web?testid=12"
string[] test2 = test.Split('//');
string test = test2[0] + "//" + test2[1] + "/" + test2[2];
Regex.Replace(test, "[^:]//", "/");
you can use stringbuilder as well.
StringBuilder b =new StringBuilder();
b.Replace("/","//",int startindex,int count);
Simply remove one of the last slashes with String.Remove():
string test="http://www.test.com//web?testid=12";
string output = test.Remove(test.LastIndexOf("//"), 1);
var http = "http://someurl//data";
var splitindex = http.IndexOf("/") + 1;
var res = http.Substring(splitindex+1, (http.Length-1) - splitindex).Replace("//","/");
http = "http://" + res;
Or
StringBuilder strBlder = new StringBuilder();
strBlder.Append("http://someurl//data");
//use the previously used variable splitindex
strBlder.Replace("//", "/", splitindex + 1, (http.Length) - splitindex);

Categories

Resources