Split a string that contains "\" - c#

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.

Related

Extract string list from a long string using prefix pattern in C#

I have a very big string with a lot of usernames. I want to extract the names from the string. That means I have one big string with lot of names in it. At the end I want every username in a string array.
An example of the string:
blablablabla#User;\u0004User\username,blablablablablablablabla#User;\u0004User\anotherusername,#Viewblablablablablablablabla
Search for: u0004User\
Save all charractes until , is found in the string array
Pseudocode:
string [] array = new string []{};
int i = 0;
foreach (var c in bigdata)
{
if(c == "u0004User\")
{
array[i] = c.AllCharactersUntil(',');
i++;
//AllCharactersUntil is a pseudo function
}
}
You can use string.IndexOf to find the index of "u0004User\" then again to find the following comma. Then use string.Substring to get the name. Keeping track of the current index and using it to tell IndexOf where to start searching from.
string bigdata =
#"blablablabla#User;\u0004User\username,blablablablablablablabla#User;\u0004User\anotherusername,#Viewblablablablablablablabla";
string searchValue = #"u0004User\";
int index = 0;
List<string> names = new List<string>();
while (index < bigdata.Length)
{
index = bigdata.IndexOf(searchValue, index);
if (index == -1) break;
int start = index + searchValue.Length;
int end = bigdata.IndexOf(',', start);
if (end == -1) break;
names.Add(bigdata.Substring(start, end - start));
index = end + 1;
}
Console.WriteLine(string.Join(", ", names));
That will give you the following output
username, anotherusername
NOTE
I've assumed that the "\u0004" values are those 6 characters and not a single unicode character. If it is a unicode character then you need the following change
string searchValue = "\u0004User\\";
Here's a simple result:
string input = "blablablabla#User;\\u0004User\username,blablablablablablablabla#User;\\u0004User\anotherusername,#Viewblablablablablablablabla";
List<string> userNames = new List<string>();
foreach (Match match in Regex.Matches(input, #"(u0004User\\)(.*?),", RegexOptions.IgnoreCase))
{
string currentUserName = match.Groups[2].ToString();
userNames.Add(currentUserName); // Add UserName to List
}

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);

Split and replace string

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);

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