Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the below code i want the string value to be comma separated but it produces the result like testtest1test2 .But i want to display like test,test1,test2.Pls help me.
string Save=string.Empty;
for (int i = 0; i < files.Count; i++)
{
//i=0 test ,i=1 test1....
Save += nFIleUpload.OrgFileName;// display value like testtest1test2..
}
string s = string.Join(",", Save);
Change this code
string Save=string.Empty;
for (int i = 0; i < files.Count; i++)
{
Save += nFIleUpload.OrgFileName;// display value like testtest1test2..
}
string s = string.Join(",", Save);
to the following
var Save = new List<string>();
for (int i = 0; i < files.Count; i++)
{
Save.Add(nFIleUpload.OrgFileName);// display value like testtest1test2..
}
var s = string.Join(",", Save);
And to go off of MethodMan's answer, when you get tired of seeing the same value added to Save for each iteration, make sure to use that index.
var Save = new List<string>();
for (int i = 0; i < files.Count; i++)
{
Save.Add(nFIleUpload[i].OrgFileName);// display value like testtest1test2..
}
var s = string.Join(",", Save);
If nFIleUpload is actually the variable that holds the strings.. is it the files variable? Who watches the watchmen? These are the questions to ask..
Try it using an array, for sample:
string[] save = new string[files.Count];
for (var i = 0; i < files.Count; i++)
save[i] = nFIleUpload.OrgFileName;
// join all values
string s = string.Join(",", save);
Or use a stringBulder which is better to concat strings, for sample:
// define the stringBuilder
StringBuilder text = new StringBuilder();
// define the loop to concat all values separated by ',' comma
for (var i = 0; i < files.Count; i++)
text.AppendFormat("{0},", nFIleUpload.OrgFileName);
// get the output
string s = text.ToString();
// remove the last comma if necessary
if (s.EndsWith(","))
s = s.Remove(s.Length - 1);
Related
I read strings from text file, and among the strings there is one: "15121 ♥☺020 000000/=n531☻".
I use .Contain() method to spot ♥☺☻ symbols in the string, but it doesn't recognize them. For ♥,☺,☻ I also tried \u2665, \u263a, \u263b (as arguments for .Contain()), but none of them were recognized.
Moreover, I copied the string (from console output window) and pasted it into my code to compare symbols one by one.
string s = "15121 ♥☺020 000000/=n531☻"; // the same with "15121 \u2665\u263a020 000000/=n531\u263b"
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
This is what I got:
What may be wrong and how do I recognize those symbols?
UPDATE: The input file I read strings from is a usual text file, and the strings inside looks like these (txt opened in Notepad):
As you can see, there is THE string among the others.
I don't use any encoding when reading the txt, and to specify how I do read the file and what the line is, here is my code:
string[] lines = File.ReadAllLines(path + target_file_name);
var list = new List<string>(lines);
for (int i = 0; i < list.Count; i++)
{
string line = list[i];
if (line.Length > 21)
{
Console.WriteLine(line);
if (line.Contains("/=n")) //used just to catch THE string
{
var line_b = Encoding.Unicode.GetBytes(line);
Console.WriteLine($"{line_b} : line = {line}");
foreach (byte m in line_b)
{
Console.Write(m + " ");
}
string s = "AAXX 15121 ♥☺020 000000/=n531☻";
Console.WriteLine();
var s_b = Encoding.Unicode.GetBytes(s);
Console.WriteLine($"{s_b} : s = {s}");
foreach (byte n in s_b)
{
Console.Write(n + " ");
}
Console.WriteLine();
for (int j = 0; j < s.Length; j++)
{
Console.WriteLine($"{line[j]} == {s[j]}: {line[j].Equals(s[j])}");
}
}
Reading all the lines from txt and converting them to List is a must for me. Thus, the line is a string line from initial txt file.
I have dumped the bytes of the inout text string var b = Encoding.Unicode.GetBytes(line); and compare with my literal (#pm100), and here is the result. Not quite sure what it does give me:
I'm sorry, I'm not willing to publish my code, and I may not understand some of your suggestions for I'm not very proficient in C# (and coding in general). So I would appreciate any further help as it is, if possible.
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(")", ""));
}
I want to include two text box texts to one text box like this
both of them are multiline.
But I want special form of include, in other words I want to include them like this
textbox 1 texts: '' help''' '' other''
textbox 2 texts:' 1' '2' '' 3''
results: help1 _ help2 _ help3
other1_other2_other3
Multiline textboxes return a string array with the lines in the Lines property. You could do something like this
string[] words = textBox1.Lines;
string[] numbers = textBox2.Lines;
var resultLines = new string[words.Length];
var sb = new StringBuilder();
for (int i = 0; i < words.Length; i++) {
sb.Length = 0; // Reset StringBuilder for the next line.
for (int j = 0; j < numbers.Length; j++) {
sb.Append(words[i]).Append("-").Append(numbers[j]).Append("_");
}
if (sb.Length > 0) {
sb.Length--; // remove the last "_"
}
resultLines[i] = sb.ToString();
}
resultsTextBox.Lines = resultLines;
First we get the words and numbers arrays. Then we create a new array for the result. Since we want a result line for each word, we make it words.Length in size.
Then we loop through the words. We use a StringBuilder to build our new lines. This is more efficient as concatenation strings with +, as it minimizes copy operations and memory allocations.
In a nested loop we put the words and numbers together.
An elegant way to solve your issue is to make use of the String.Join method in C#. I'm adding this answer because I'm a big fan of the method and think it must be part of some answer to this question because it has to do with combining strings.
Here's the code that I'd use to solve the challenge:
string[] firstInput = textBox1.Lines;
string[] secondInput = textBox2.Lines;
var combinedInputs = new string[firstInput.Length];
var combinedLine = new string[secondInput.Length];
for(int i = 0; i < firstInput.Length; i++)
{
for(int j = 0; j < secondInput.Length; j++)
{
combinedLine[j] = firstInput[i] + secondInput[j];
}
//Combine all values of combinedLine with a '-' in between and add this to combinedInputs.
combinedInputs[i] = String.Join("-", combinedLine);
}
outputTextBox.Lines = combinedInputs; //the resulting output
I hope this answer helped aswell. And I'd like to give credits to Olivier for explaining the textbox part. Another thing that I'd like to add is that this answer isn't meant to be the most efficient, but is meant to be easy to read and understand.
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)));
I have a problem with C#.
I am writing code to search a text file until it finds a certain word, then the code should move three lines and read the fourth, then continue the search to find the certain word again.
Now I don't know how to navigate through the file (forward and backward) to the line I want.
Can anybody help?
You can do something like this:
var text = File.ReadAllLines("path"); //read all lines into an array
var foundFirstTime = false;
for (int i = 0; i < text.Length; i++)
{
//Find the word the first time
if(!foundFirstTime && text[i].Contains("word"))
{
//Skip 3 lines - and continue
i = Math.Min(i+3, text.Length-1);
foundFirstTime = true;
}
if(foundFirstTime && text[i].Contains("word"))
{
//Do whatever!
}
}
// read file
List<string> query = (from lines in File.ReadLines(this.Location.FullName, System.Text.Encoding.UTF8)
select lines).ToList<string>();
for (int i = 0; i < query.Count; i++)
{
if (query[i].Contains("TextYouWant"))
{
i = i + 3;
}
}
Your requirements state that you are searching for a specific word. If that is true and you are not instead looking for a specific string, then the checked answer on this is wrong. Instead you should use:
string[] lines = System.IO.File.ReadAllLines("File.txt");
int skip = 3;
string word = "foo";
string pattern = string.Format("\\b{0}\\b", word);
for (int i = 0; i < lines.Count(); i++)
{
var match = System.Text.RegularExpressions.Regex.IsMatch(lines[i], pattern);
System.Diagnostics.Debug.Print(string.Format("Line {0}: {1}", Array.IndexOf(lines, lines[i], i) + 1, match));
if (match) i += skip;
}
If you use the string.contains method and the word you are searching for is "man", while your text somewhere contains "mantle" and "manual", the string.contains method will return as true.