Split and replace string - c#

I have a string in a format:
string path="/fm/Templates/testTemplate/css/article.jpg";
I want to split this with second '/' and replace with '/' to '\\' want a result like this.
string newPath="\\Templates\\testTemplate\\css\\article.jpg";
My path is dynamic created so folder hierarchy is not fixed.
What is the best way to do this.May I split first string path with / and go to loop to re-concate this and repalce with '/' to '\\' or there any easy way I am missing.

Can't you just use String.Replace?

string path = "/fm/Templates/testTemplate/css/article.jpg";
path = path.Substring(path.IndexOf('/', 1)).Replace("/", "\\\\");

If you're working with individual segments of your path (and not just replacing the direction of the slashes), the System.Uri class will help (.Segments property).
Eg from MSDN
Uri uriAddress1 = new Uri("http://www.contoso.com/title/index.htm");
Console.WriteLine("The parts are {0}, {1}, {2}", uriAddress1.Segments[0], uriAddress1.Segments[1], uriAddress1.Segments[2]);

You can use the following code.
string path="/fm/Templates/testTemplate/css/article.jpg";
string newpath = path.Replace("/fm", string.Empty).Replace("/","\\");
Thanks

Try this,
string path = "/fm/Templates/testTemplate/css/article.jpg";
string[] oPath = path.Split('/');
string newPath = #"\\" + string.Join(#"\\", oPath, 2, oPath.Length - 2);
Console.WriteLine(newPath);

Is your string manipulation really so time critical that you need to do everything at once? It's much easier just to break it down into parts:
// First remove the leading /../ section:
path = Regex.Replace("^/[^/]*/", "", path);
// Then replace any remaining /s with \s:
path = path.Replace("/", "\\");

Try with this:
public static int nthOccurrence(String str, char c, int n)
{
int pos = str.IndexOf(c, 0);
while (n-- > 0 && pos != -1)
pos = str.IndexOf(c, pos + 1);
return pos;
}
string path = "/fm/Templates/testTemplate/css/article.jpg";
int index = nthOccurrence(path, '/', 1);
string newpath = path.Substring(index).Replace("/", "\\");
OUTPUT: "\\Templates\\testTemplate\\css\\article.jpg"

You may create a new string after removing the first item from the path. The following will give you the desired result. It may be optimized.
You can try:
Split the string on char / and remove empty entries.
Get a new array after disregarding the first item from the split array
Use string.Join to create the new string with \\ as separator.
Here is the code:
string path = "/fm/Templates/testTemplate/css/article.jpg";
string[] temp = path.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
var newTemp = temp.AsEnumerable().Where((r, index) => index > 0);
string newPath2 = string.Join("\\", newTemp);

Related

Split a string that contains "\"

I'm trying to split a string that represents a filepath, so the path contains pictures. For example should the pathstring #c:\users\common\pictures\2008 be converted to pictures\2008. The problem that I encounter is that when I use \ in a string it gives me an error. Sorry for the dumb question, m new with C#. This is what I've done so far:
string path = "#c:\users\common\pictures\2008";
string[] subs = path.Split('\');
int count = 0;
while(subs[count] != "pictures")
{
count++;
}
string newPath = "";
for (int i = count; i < subs.Length; i++)
{
newPath += "\" + subs[i];
}
Console.WriteLine(newPath);
That's because \ is a reserved char in C# so you must use it in this way '\\'
In case of string you can add before the special char #
In case of char you have to double it \\
See the documentation
string path = #"#c:\users\common\pictures\2008";
string[] subs = path.Split('\\');
int count = 0;
while (subs[count] != "pictures")
{
count++;
}
string newPath = "";
for (int i = count; i < subs.Length; i++)
{
newPath = Path.Combine(newPath ,subs[i]);
}
Console.WriteLine(newPath);
Also prefer the use, if possible, of Path.Combine since it take care of the escape char for you.
Firstly, C# treats the '\' character as an escape character in a string, so you need to double it up to work.
string path = "#c:\\users\\common\\pictures\\2008";
string newPath = path.Substring(path.IndexOf("\\pictures\\") + 1);
What this does is take a substring of the 'path' starting at point after where "\pictures\" starts (because you don't want the initial '\').
Or this:
string path = "#c:\\users\\common\\pictures\\2008";
string[] subs = path.Split('\\');
int count = Array.IndexOf(subs, "pictures");
string newPath = String.Join("\\", subs, subs.Length - count);
Takes the path, splits into an array of the folders, finds the index of the element in the array that is 'pictures' and then joins the array starting at that point.

string.PadRight() doesn't seem to work in my code

I have a Powershell output to re-format, because formatting gets lost in my StandardOutput.ReadToEnd().There are several blanks to be removed in a line and I want to get the output formatted readable.
Current output in my messageBox looks like
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
What I want is
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
What am I doing wrong?
My C# knowledge still is basic level only
I found this question here, but maybe I don't understand the answer correctly. The solution doesn't work for me.
Padding a string using PadRight method
This is my current code:
string first = "";
string last = "";
int idx = line.LastIndexOf(" ");
if (idx != -1)
{
first = line.Substring(0, idx).Replace(" ","").PadRight(10, '~');
last = line.Substring(idx + 1);
}
MessageBox.Show(first + last);
String.PadLeft() first parameter defines the length of the padded string, not padding symbol count.
Firstly, you can iterate through all you string, split and save.
Secondly, you should get the longest string length.
Finally, you can format strings to needed format.
var strings = new []
{
"Microsoft.MicrosoftJigsaw All",
"Microsoft.MicrosoftMahjong All"
};
var keyValuePairs = new List<KeyValuePair<string, string>>();
foreach(var item in strings)
{
var parts = item.Split(new [] {" "}, StringSplitOptions.RemoveEmptyEntries);
keyValuePairs.Add(new KeyValuePair<string, string>(parts[0], parts[1]));
}
var longestStringCharCount = keyValuePairs.Select(kv => kv.Key).Max(k => k.Length);
var minSpaceCount = 5; // min space count between parts of the string
var formattedStrings = keyValuePairs.Select(kv => string.Concat(kv.Key.PadRight(longestStringCharCount + minSpaceCount, ' '), kv.Value));
foreach(var item in formattedStrings)
{
Console.WriteLine(item);
}
Result:
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
The PadRight(10 is not enough, it is the size of the complete string.
I would probably go for something like:
string[] lines = new[]
{
"Microsoft.MicrosoftJigsaw All",
"Microsoft.MicrosoftMahjong All"
};
// iterate all (example) lines
foreach (var line in lines)
{
// split the string on spaces and remove empty ones
// (so multiple spaces are ignored)
// ofcourse, you must check if the splitted array has atleast 2 elements.
string[] splitted = line.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// reformat the string, with padding the first string to a total of 40 chars.
var formatted = splitted[0].PadRight(40, ' ') + splitted[1];
// write to anything as output.
Trace.WriteLine(formatted);
}
Will show:
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
So you need to determine the maximum length of the first string.
Assuming the length of second part of your string is 10 but you can change it. Try below piece of code:
Function:
private string PrepareStringAfterPadding(string line, int totalLength)
{
int secondPartLength = 10;
int lastIndexOfSpace = line.LastIndexOf(" ");
string firstPart = line.Substring(0, lastIndexOfSpace + 1).Trim().PadRight(totalLength - secondPartLength);
string secondPart = line.Substring(lastIndexOfSpace + 1).Trim().PadLeft(secondPartLength);
return firstPart + secondPart;
}
Calling:
string line1String = PrepareStringAfterPadding("Microsoft.MicrosoftJigsaw All", 40);
string line2String = PrepareStringAfterPadding("Microsoft.MicrosoftMahjong All", 40);
Result:
Microsoft.MicrosoftJigsaw All
Microsoft.MicrosoftMahjong All
Note:
Code is given for demo purpose please customize the totalLength and secondPartLength and calling of the function as per your requirement.

Trim a string in c# after special character

I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

How to delete words between specified chars?

I want to create a method that reads from every line from a file. Next, it has to check between the pipes and determine if there are words that are more than three characters long, and are only numbers. In the file are strings organized like this:
What's going on {noway|that's cool|1293328|why|don't know|see}
With this sentence, the software should remove 1293328.
The resulting sentence would be:
What's going on {noway|that's cool|don't know}
Until now I am reading every line from the file and I made the functions that determine if the words between | | have to be deleted or not (checking a string like noway,that's cool, etc)
I don't know how to get the strings between the pipes.
You can split a string by a character using the Split method.
string YourStringVariable = "{noway|that's cool|1293328|why|don't know|see}";
YourStringVariable.Split('|'); //Returns an array of the strings between the brackets
What's about:
string RemoveValues(string sentence, string[] values){
foreach(string s in values){
while(sentence.IndexOf("|" + s) != -1 && sentence.IndexOf("|" + s) != 0){
sentence = sentence.Remove(sentence.IndexOf("|" + s), s.Lenght + 1);
}
}
return sentence;
}
In your case:
string[] values = new string[3]{ "1293328", "why", "see" };
string sentence = RemoveValues("noway|that's cool|1293328|why|don't know|see", values);
//result: noway|that's cool|don't know
string YourStringVariable = "{noway|that's cool|1293328|why|don't know|see}";
string[] SplitValue=g.Split('|');
string FinalValue = string.Empty;
for (int i = 0; i < SplitValue.Length; i++)
{
if (!SplitValue[i].ToString().Any(char.IsDigit))
{
FinalValue += SplitValue[i]+"|";
}
}

strip out digits or letters at the most right of a string

I have a file name: kjrjh20111103-BATCH2242_20111113-091337.txt
I only need 091337, not the txt or the - how can I achieve that. It does not have to be 6 numbers it could be more or less but will always be after "-" and the last ones before ."doc" or ."txt"
You can either do this with a regex, or with simple string operations. For the latter:
int lastDash = text.LastIndexOf('-');
string afterDash = text.Substring(lastDash + 1);
int dot = afterDash.IndexOf('.');
string data = dot == -1 ? afterDash : afterDash.Substring(0, dot);
Personally I find this easier to understand and verify than a regular expression, but your mileage may vary.
String fileName = kjrjh20111103-BATCH2242_20111113-091337.txt;
String[] splitString = fileName.Split ( new char[] { '-', '.' } );
String Number = splitString[2];
Regex: .*-(?<num>[0-9]*). should do the job. num capture group contains your string.
The Regex would be:
string fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
string fileMatch = Regex.Match(fileName, "(?<=-)\d+", RegexOptions.IgnoreCase).Value;
String fileName = "kjrjh20111103-BATCH2242_20111113-091337.txt";
var startIndex = fileName.LastIndexOf('-') + 1;
var length = fileName.LastIndexOf('.') - startIndex;
var output = fileName.Substring(startIndex, length);

Categories

Resources