C# String Query how many / characters it contains - c#

I would like to inquire how many / are in a string.
When I get the number how can I get all folders now (So how can I separate them)?
For Example: Folder/Cats (1 / = 2 folders) String1 Folder, String2 Cats
I first ask whether there is any / in the string
Regex myRegex = new Regex(#"[/]{1}", RegexOptions.IgnoreCase);
Match matchSuccess = myRegex.Match(string);
if (matchSuccess.Success)
{
// Create several folders
// Folder/Cats....
}
else
{
// Create only one folder
// Folder
}
String Examples:
• Folder/UnderFolder/Cat/Pics
• NewFolder/Cats
• Folder
• NewFolder

To count the number of occurrence of /, what you can do is use the Split.Length
int count = folderString.Split('/').Length - 1;
As for the name of the folders, you can get them by calling the index
folderString.Split('/')[index]
Here's the whole console app code for that:
string folderString = #"Folder/UnderFolder/Cat/Pics";
int count = folderString.Split('/').Length - 1;
for(int x = 0; count >= x; x++)
{
Console.WriteLine(folderString.Split('/')[x]);
}
Console.WriteLine("Count: {0}", count);
The output would be:
Folder
UnderFolder
Cat
Pics
Count: 3
Hope it helps!

Just use standart CreateDirectory method.
Directory.CreateDirectory(#"C:\folder1\folder2\folder3\folder4")

Why do you want to go for regex. Finding any characters in a string or splitting a string is very easy. Sample code for your case :
string input = #"Folder/UnderFolder/Cat/Pics";
string[] values = input.Split('/');
int numOfSlashes = values.Length - 1;
Console.WriteLine("Number of Slashes = " + numOfSlashes);
foreach (string val in values)
{
Console.WriteLine(val);
}

//Your folder path
string yourFolderPath= #"C:/Folder/UnderFolder/Cat/Pics";
//If you want to count number of folders in the given folder path
int FolderCount = yourFolderPath.Count(s => s == '/');
//If you want to create folder you can use directly below code
Directory.CreateDirectory(yourFolderPath);

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.

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
}

SubString editing

I've tried a few different methods and none of them work correctly so I'm just looking for someone to straight out show me how to do it . I want my application to read in a file based on an OpenFileDialog.
When the file is read in I want to go through it and and run this function which uses Linq to insert the data into my DB.
objSqlCommands.sqlCommandInsertorUpdate
However I want to go through the string , counting the number of ","'s found . when the number reaches four I want to only take the characters encountered until the next "," and do this until the end of the file .. can someone show me how to do this ?
Based on the answers given here my code now looks like this
string fileText = File.ReadAllText(ofd.FileName).Replace(Environment.NewLine, ",");
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();
foreach (char c in fileText.ToArray())
{
idx++;
if (c == ',')
{
counter++;
}
if (counter == 4)
{
string x = fileText.Substring(idx);
foo.Add(fileText.Substring(idx, x.IndexOf(',')));
counter = 0;
}
}
foreach (string s in foo)
{
objSqlCommands.sqlCommandInsertorUpdate("INSERT", s);//laClient[0]);
}
However I am getting an "length cannot be less than 0" error on the foo.add function call , any ideas ?
A Somewhat hacky example. You would pass this the entire text from your file as a single string.
string str = "1,2,3,4,i am some text,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20";
int counter = 0;
int idx = 0;
List<string> foo = new List<string>();
foreach (char c in str.ToArray())
{
idx++;
if (c == ',')
{
counter++;
}
if (counter == 4)
{
string x = str.Substring(idx);
foo.Add(str.Substring(idx, x.IndexOf(',')));
counter = 0;
}
}
foreach(string s in foo)
{
Console.WriteLine(s);
}
Console.Read();
Prints:
i am some text
9
13
17
As Raidri indicates in his answer, String.Split is definitely your friend. To catch every fifth word, you could try something like this (not tested):
string fileText = File.ReadAllText(OpenDialog.FileName).Replace(Environment.NewLine, ",");
string words[] = fileText.Split(',');
List<string> everFifthWord = new List<string>();
for (int i = 4; i <= words.Length - 1, i + 5)
{
everyFifthWord.Add(words[i]);
}
The above code reads the selected file from the OpenFileDialog, then replaces every newline with a ",". Then it splits the string on ",", and starting with the fifth word takes every fifth word in the string and adds it to the list.
File.ReadAllText reads a text file to a string and Split turns that string into an array seperated at the commas:
File.ReadAllText(OpenDialog.FileName).Split(',')[4]
If you have more than one line use:
File.ReadAllLines(OpenDialog.FileName).Select(l => l.Split(',')[4])
This gives an IEnumerable<string> where each string contains the wanted part from one line of the file
It's not clear to me if you're after every fifth piece of text between the commas or if there are multiple lines and you want only the fifth piece of text on each line. So I've done both.
Every fifth piece of text:
var text = "1,2,3,4,i am some text,6,7,8,9"
+ ",10,11,12,13,14,15,16,17,18,19,20";
var everyFifth =
text
.Split(',')
.Where((x, n) => n % 5 == 4);
Only the fifth piece of text on each line:
var lines = new []
{
"1,2,3,4,i am some text,6,7",
"8,9,10,11,12,13,14,15",
"16,17,18,19,20",
};
var fifthOnEachLine =
lines
.Select(x => x.Split(',')[4]);

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]+"|";
}
}

Getting parts of a string and combine them in C#?

I have a string like this: C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg
Now, what I want to do is to dynamically combine the last 4 numbers, in this case its 10000080 as result. My idea was ti split this and combine them in some way, is there an easier way? I cant rely on the array index, because the path can be longer or shorter as well.
Is there a nice way to do that?
Thanks :)
A compact way using string.Join and Regex.Split.
string text = #"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
string newString = string.Join(null, Regex.Split(text, #"[^\d]")); //10000080
Use String.Split
String toSplit = "C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
String[] parts = toSplit.Split(new String[] { #"\" });
String result = String.Empty;
for (int i = 5, i > 1; i--)
{
result += parts[parts.Length - i];
}
// Gives the result 10000080
You can rely on array index if the last part always is the filename.
since the last part is always
array_name[array_name.length - 1]
the 4 parts before that can be found by
array_name[array_name.length - 2]
array_name[array_name.length - 3]
etc
If you always want to combine the last four numbers, split the string (use \ as the separator), start counting from the last part and take 4 numbers, or the 4 almost last parts.
If you want to take all the digits, just scan the string from start to finish and copy just the digits to a new string.
string input = "C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
string[] parts = toSplit.Split(new char[] {'\\'});
IEnumerable<string> reversed = parts.Reverse();
IEnumerable<string> selected = reversed.Skip(1).Take(4).Reverse();
string result = string.Concat(selected);
The idea is to extract the parts, reverse them to keep only the last 4 (excluding the file name) and re reversing to rollback to the initial order, then concat.
Using LINQ:
string path = #"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg";
var parts = Path.GetDirectoryName(path).Split('\\');
string numbersPart = parts.Skip(parts.Count() - 4)
.Aggregate((acc, next) => acc + next);
Result: "10000080"
var r = new Regex(#"[^\d+]");
var match = r
.Split(#"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg")
.Aggregate((i, j) => i + j);
return match.ToString();
to find the number you can use regex:
(([0-9]{2})\\){4}
use concat all inner Group ([0-9]{2}) to get your searched number.
This will always find your searched number in any position in the given string.
Sample Code:
static class TestClass {
static void Main(string[] args) {
string[] tests = { #"C:\Projects\test\whatever\files\media\10\00\00\80\test.jpg",
#"C:\Projects\test\whatever\files\media\10\00\00\80\some\foldertest.jpg",
#"C:\10\00\00\80\test.jpg",
#"C:\10\00\00\80\test.jpg"};
foreach (string test in tests) {
int number = ExtractNumber(test);
Console.WriteLine(number);
}
Console.ReadLine();
}
static int ExtractNumber(string path) {
Match match = Regex.Match(path, #"(([0-9]{2})\\){4}");
if (!match.Success) {
throw new Exception("The string does not contain the defined Number");
}
//get second group that is where the number is
Group #group = match.Groups[2];
//now concat all captures
StringBuilder builder = new StringBuilder();
foreach (var capture in #group.Captures) {
builder.Append(capture);
}
//pares it as string and off we go!
return int.Parse(builder.ToString());
}
}

Categories

Resources