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
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
i want to add all the numbers from notepad to the array, give me the solution .
notepad file content see photos:
If what you are trying to do is parse every number in the text file of yours to a Int32 and have a int array.
You would want to use File.ReadAllLines, to read every line from the file, string.Split each line by ';' and then parse every string number to a Int32:
string[] lines = File.ReadAllLines("numbers.txt");
List<int> numbers = new List<int>();
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
if (!string.IsNullOrEmpty(line))
{
string[] stringNumbers = line.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
for (int j = 0; j < stringNumbers.Length; j++)
{
if (!int.TryParse(stringNumbers[j], out int num))
{
throw new OperationCanceledException(stringNumbers[j] + " was not a number.");
}
numbers.Add(num);
}
}
}
int[] array = numbers.ToArray();
If you are looking to have a string array of the numbers then just do as the above, but without the int.TryParse and have numbers be a List<string> instead of List<int>
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]);
}
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." : "";
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)));
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
I have an issue with this:
When John was a little kid he didn't have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could... he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.
Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it. The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn't care about whether letters are uppercase or lowercase, so that doesn't affect the beauty of a letter. (Uppercase 'F' is exactly as beautiful as lowercase 'f', for example.)
You're a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file has a sentence. E.g.
ABbCcc
Good luck in the Facebook Hacker Cup this year!
Ignore punctuation, please :)
Sometimes test cases are hard to make up.
So I just go consult Professor Dalves
Output sample:
Print out the maximum beauty for the string. E.g.
152
754
491
729
646
And here is my code in C#:
static void Main(string[] args)
{
StreamReader myR = new StreamReader(args[0]);
List<string> myL = new List<string>();
while (!myR.EndOfStream)
{
myL.Add(myR.ReadLine());
}
foreach (string item in myL)
{
int maxBeautifulNum = 0;
string temp = item.ToLower();
char[] myC = temp.ToCharArray();
string[] tempS = new string[myC.Length];
string tempCount;
for (int i = 0; i < myC.Length; i++)
{
if ((myC[i] >= 'a' && myC[i] <= 'z') || (myC[i] >= 'A' && myC[i] <= 'Z'))
{
tempS[i] = myC[i].ToString();
}
}
tempS = tempS.Where(w => !string.IsNullOrWhiteSpace(w)).ToArray();
List<string> myCounterList = new List<string>();
while(tempS.Length >= 1)
{
int count = 0;
tempCount = tempS[0];
for (int j = 0; j < tempS.Length; j++)
{
if (tempS[j] == tempCount)
{
count++;
}
}
myCounterList.Add(count.ToString());
tempS = tempS.Where(w => w != tempCount).ToArray();
}
string[] myCounterString = myCounterList.ToArray();
Array.Sort(myCounterString);
Array.Reverse(myCounterString);
for (int i = 0; i < myCounterString.Length; i++)
{
maxBeautifulNum += (26 - i) * int.Parse(myCounterString[i]);
}
Console.WriteLine(maxBeautifulNum);
}
}
It run right with only some tests, but I can't find out else test for it runs failed.
Any one can show me test for my code run failed.
Here's a basic LINQPad program that calculates the "beauty" of a string:
void Main()
{
string[] inputs =
{
"a",
"z",
"A test",
"A TEST",
"a test"
};
foreach (var input in inputs)
{
var beauty =
(from c in input
let C = char.ToUpper(c)
where C >= 'A' && C <= 'Z'
select (int)(C - 'A') + 1).Sum();
beauty.Dump(input);
}
}
All the magic is in that single LINQ statement inside the loop there.
Also, to read all the lines from a file, use this:
string[] lines = File.ReadAllLines(fileName);