Why parsing string of path name is not working? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code:
List<string> dirParts = new List<string>();
int index = 0;
for (int i = 0; i < dirName.Length; i++)
{
index = dirName.IndexOf("/");
string dironly = dirName.Substring(index, dirName.Length - index);
dirParts.Add(dironly);
}
dirName for example contains d/1/2/3/4/5
So I need that in the List dirParts in the end I will have in index 0 d, in index 1 d/1, in index 2 d/1/2, in index 3 d/1/2/3, in index 4 d/1/2/3/4, in index 5 d/1/2/3/4/5
So when I look on the List it should look like this:
d
d/1
d/1/2
d/1/2/3
d/1/2/3/4
d/1/2/3/4/5

Possible implementation:
List<string> dirParts = new List<string>();
int index = -1;
while (true) {
index = dirName.IndexOf("/", index + 1);
if (index < 0) {
dirParts.Add(dirName);
break;
}
else
dirParts.Add(dirName.Substring(0, index));
}

Apart from the fact that this kind of path manipulation is best left to the library, lest your code breaks on strange exceptional directory names, your code works as it does because you look everytime for the same "/".
You should search after the last one:
index = dirName.IndexOf("/", index+1);

If you really want to do it that way:
for (int i = 0; i < dirName.Length; i++) {
index = dirName.IndexOf("/", index);
if (index == -1)
i = index = dirName.Length; //last one
dirParts.Add(dirName.Substring(0, index++));
}

If it's a directory, I like to use Path library personally. The only issue would be the use of / over \ in directory name, so you'd have to call .Replace before inserting:
var orig = "d/1/2/3/4/5"; // Original string
List<String> dirParts = new List<String>(new[]{ orig }); // start out with list of original
// Get the directory below this one. (drop off last folder)
String part = Path.GetDirectoryName(orig);
while (!String.IsNullOrEmpty(part))
{
// add it to the first entry in the list
dirParts.Insert(0, part.Replace('\\','/'));
// get the next parent folder.
part = Path.GetDirectoryName(part);
}
/* dirParts = [ "d", "d/1", "d/1/2", ... ] */
However, if you're just looking for the down and dirty LINQ approach:
var orig = "d/1/2/3/4/5";
String[] parts = orig.Split('/');
var dirParts = Enumerable.Range(1, parts.Length)
.Select (e => String.Join("/", parts.Take(e)));

Related

How to get all string "possibilities" [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Given a string like string s = "a(b)cd(ef)",
what is the best way to get a list/array containing all the following strings:
"acd",
"abcd",
"acdef",
"abcdef"
Additional information:
The order of the result doesn't matter.
The amount of parenthesis is unknown
I have tried to do this with RegEx, but didn't get very far.
There are many ways to do this, however here is an example using a mask array to keep track of the permutation state, some regex, and a few helper methods
Given
// work out the states of the combination
public static bool GetNextState(bool[] states)
{
for (var i = 0; i < states.Length; i++)
if ((states[i] = !states[i]) == true)
return false;
return true;
}
// Create the combination
public static string Join(string[] split, string[] matches, bool[] states)
{
var sb = new StringBuilder();
for (var i = 0; i < states.Length; i++)
sb.Append(split[i] + (states[i]? matches[i]:""));
sb.Append(split.Last());
return sb.ToString();
}
// enumerate the results
public static IEnumerable<string> Results(string input)
{
var matches = Regex.Matches(input, #"\(.+?\)")
.Select(x => x.Value.Trim('(', ')'))
.ToArray();
var split = Regex.Split(input, #"\(.+?\)");
var states = new bool[matches.Length];
do {
yield return Join(split, matches, states);
} while (!GetNextState(states));
}
Usage
string s = "a(b)cd(ef)";
foreach (var result in Results(s))
Console.WriteLine(result);
Output
acd
abcd
acdef
abcdef
Full Demo Here
Michael Randall's answer is correct, but after some more thinking I was finally able to come up with a (probably not very good) working solution as well
string s = "a(b)cd(ef)";
List<string> result = new List<string>();
int amount = s.Split('(').Length;
amount = (int)Math.Pow(2, amount - 1);
for (int i = 0; i < amount; i++)
{
string temp = string.Copy(s);
string binaryString = Convert.ToString(i, 2).PadLeft(amount, '0');
string tempResult = "";
for (int j = 0; j < binaryString.Length && !temp.Equals(""); j++)
{
Regex regex = new Regex(#"[^(]*");
tempResult += regex.Match(temp).Value;
if (binaryString[binaryString.Length - 1 - j].Equals('1'))
{
string regexStr = #"\(([^)]*)\)";
regex = new Regex(regexStr);
tempResult += regex.Match(temp).Value;
}
if (temp.Contains(')'))
temp = temp.Substring(temp.IndexOf(')') + 1);
else temp = "";
}
result.Add(tempResult.Replace("(", "").Replace(")", ""));
}

find and extract a number from a string C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a requirement to find and extract a number contained within a string.
For example, from these strings:
"O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000"
extract :
1.2275000
2.3060000
3.3260000
....
It would be :
string temp = yourText;
List<int> numbers = new List<int>();
Regex re = new Regex(#"\d+");
Match m = re.Match(temp);
while (m.Success)
{
numbers.Add(Convert.ToInt32(m.Value));
temp = temp.Substring(m.Index + m.Length);
m = re.Match(temp);
}
First of all, you mentioned "from these strings", though you gave a single string. I am not clear about this part.
Secondly, what do you mean by extract? Do you want to find the position of a number in the string? If yes then you can simply use string search as following
string str = "O:2275000 BF:3060000 D:3260000";
int index = str.IndexOf("3060000");
if (index != -1)
{
Console.WriteLine(index);
}
else
{
Console.WriteLine("Not Found");
}
Or if the problem is stated like that: you were given a string and you want to extract the numbers out of it, then you can do it like so:
List<decimal> findNumbers(string str)
{
List<decimal> x = new List<decimal>();
string tokens = "";
foreach (char ch in str)
{
if (Char.IsNumber(ch))
{
tokens = tokens + ch;
}
if (!Char.IsNumber(ch) && !String.IsNullOrEmpty(tokens))
{
decimal num = Convert.ToDecimal(tokens);
x.Add(Convert.ToDecimal(num));
tokens = "";
}
}
if (String.IsNullOrEmpty(tokens))
{
x.Add(Convert.ToDecimal(tokens));
}
return x;
}
this function returns the list of numbers available in the string.
We can try using string split here:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
foreach (string n in numbers)
{
Console.WriteLine(n);
}
This prints:
2275000
3060000
3260000
You can do this in a single line with Linq.
string numbers = "O:2275000 BF:3060000 D:3260000 E:3472000 I:3918000 T:4247000 UF:4777000 A:4904000 AD:5010000 X:5243000 G:21280000";
List<int> list = numbers.Split(' ').Select(x => Convert.ToInt32(string.Concat(x.Where(Char.IsDigit)))).ToList();
Tim Biegeleisen's answer is correct except it does not produce floating point output as you mentioned in your question. In his answere, just replace foreach loop with for statement, like this:
string input = "O:2275000 BF:3060000 D:3260000";
string[] parts = input.Split(' ');
string[] numbers = parts
.Select(s => s.Split(':')[1])
.ToArray();
for(int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("{0}.{1}", i+1, numbers[i]);
}

how to concatenate the list elements into a string using forloop in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have list object and I want to make a message by concatenating the values.
In list there are two properties called area and filled. I need such way that model[0].area = model[0].filled and model[0].area = model[1].filled.
According to the condition array list object may be 0 to 5 elements
Example: Area1 = 8.12 and Area2 = 7.8 filled, data type filled - double , area = string
List<MHViewModel> model = getMHDetails();
model = model.Where(x => x.Filled > 8).ToList();
int numbers = model.Count;
string data = "";
if (numbers > 0)
{
data = model[0].Area + model[0].Filled.ToString("0.00") ;
}
You can keep using Linq and put string.Join to concat:
var concat = string.Join(" and ", model
.Select((item, index) => $"Area{index + 1}={item.Filled:F2}"));
string result = string.IsNullOrEmpty(concat) ? "" : $"{concat} filled.";
If you insist on for loop:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < model.Count; ++i) {
if (sb.Length > 0)
sb.Append(" and ");
sb.Append($"Area{i + 1}={model[i].Filled:F2}");
}
string result = sb.Length > 0 ? $"{sb.ToString()} filled." : "";

find the largest substring that contains all of occurrence of a character [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to find out largest sub string that contains all of occurrence of a character in C#.
Example - Input string : "my name is granar"
Nee to find out largest sub string that contains all of occurrence of a character "a", the result is "ame is grana"
Please help me in algorithm?
This should do it:
var text = "my name is granar";
var firstA = text.IndexOf("a");
var LastA = text.LastIndexOf("a");
int length = LastA - firstA + 1;
if (firstA != -1)
var result = text.Substring(firstA, length);
Algorithm: int begin = -1, end = -1
In a for loop
save first index of 'a' in begin and end
keep updating end every time you encounter 'a'
strinput.substring(begin,end)
static void Main(string[] args)
{
int begin = -1, end = -1;
string input = "my name is granar";
bool isfirst = true;
for (int i = 0; i < input.Length; i++)
{
if(input[i] == 'x')
{
if (isfirst)
{
begin = i;
end = i;
isfirst = false;
}
else
end = i;
}
}
if (begin != -1)
{
string substr = input.Substring(begin, end - begin + 1);
Console.WriteLine(substr);
}
else Console.WriteLine("Not Found");
Console.ReadKey();
}
This is a better algorithm for larger string, as we are iterating through the entire string only once.

replace string by index of this string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hello so i have a text file that looks like
45353
b
4353
b
54
54
b
5345
53453
and array list that looks like
A
B
A
how can i replace string b->A b - > b - > A ?
OUTPUT SHOUDL LOOK like
45353
A
4353
B
54
54
A
5345
53453
string content = File.ReadAllText("data.txt");
var replacements = new[] { "A", "B", "A" };
int index = 0;
string result = Regex.Replace(content, #"[a-zA-Z]+",
m => replacements.Length > index ?
replacements[index++] : m.Value);
This will execute MatchEvaluator for each found word, and replace it with value from appropriate position in replacements array.
You could use Regex.Replace(String, String, Int32) for this, execute until all of the intended replacements from arr are replaced.
var text = File.ReadAllText("file.txt");
var arr = new[] { "A", "B", "A" };
var regex = new Regex("b");
for(int i = 0; i < arr.Count; i++)
text = regex.Replace(text, arr[i].ToString(), 1);
Tip: Never answer when tired...
Read the 2nd file into an array of strings
Keep a counter initialized to 0
Read from the 1st file, every-time your data matches the replacement condition, replace it with the value at the counter and increment the counter
StreamReader sr = new StreamReader("file.txt");
int counter = 0;
List<string> arrayFromFile = new List<string>();
while(string line = sr.ReadLine())
{
if(line=='b')
{
line = abaArray[counter];
counter++;
if(counter>=abaArray.Length)
{
counter=0;
}
}
arrayFromFile.Add(line)
}
//Write back to the file

Categories

Resources