I have file names that contain numbers that need to be decremented by 1. I need code that satisfies the following pseudocode:
class ReplaceSubstrings
{
string searchFor;
string replaceWith;
Bool filenamecontainnumbers; 'file name contains numbers to be decremented by 1
int filenamenumbers; ' file name size varies from 10 to 500 - I only want to ' target integers 200 - 500
while(filenamecontainsnumbers = 1) ' maybe I should use Bool condition
ReplaceSubstrings app = new ReplaceSubstrings();
If(filenamenumbers > 200){
app.searchFor = filenamenumbers; // A very simple regular expression.
app.replaceWith = decnamenumber();
Console.WriteLine(s);
return 0;
}
void decnamenumber(){
filenamenumbers = filenamenumbers - 1;
};
or something like this!!! Help Please!!!
for "renaming" in c# you can just "move" the file: check out this http://www.dotnetperls.com/file-move
Related
I've been coding in C# (winforms) for a project for 2 weeks now. My goal is to build a GUI for an FFT-Analysis (frequency-realm).
my Problem:
I keep running into the same problem: i receive 1024 int values (one blocksize) separated by white spaces in one string via serial port and then terminated by \n into a buffer uart_buf. To obtain numeric values, i use uart_buf.split(' ') into a string[] parse_buf and then try to access a single value in ASCII-format like this: parse_buf[i] = val_buf. This i then try to form into a numeric via value = int.Parse(val_buf), without success: System.ArgumentNullException: value cant be NULL.
What I've tried:
value = int.Parse(parse_buf[i]); This returns a format exception
printing parse_buf[i] to a textbox shows an expected value (the received data is correct)
observing the main buffer uart_buf shows valid data like this: "41 30 2 0 0 0 0 0 0 0 3 40 500 69..."
starting from index 1 (or any other) instead of 0 changes nothing
What I don't get:
A single element (ergo a string) of parse_buf contains a value in text-form, e.g. "41". I want to save it to a regular string val_buf, which i should be able to parse to int. Why is every string accessed via parse_buf[i] null?
Code-Fragments:
private void displayData(object o, EventArgs e)
{
parse_buf = uart_buf.Split(' ');
tb_data.Text = parse_buf[0]; //this shows valid data in a tb
for (i = 1; i < parse_buf.Length; i++) //about 1024 loops
{
//problem area:
parse_buf[i] = val_buf;
fft = int.Parse(val_buf);
//ignore this:
f = i * 20;
chart1.Series[0].Points.AddXY(f, fft);
}
}
I usually work in C with embeded systems, so sorry for not seeing the problem instantly. Thanks.
private void DisplayData(object o, EventArgs e)
{
parse_buf = uart_buf.Split(' ');
tb_data.Text = parse_buf[0]; //this shows valid data in a tb
for (i = 0; i < parse_buf.Length; i++) //about 1024 loops
{
//problem area:
int.TryParse(parse_buf[i], out ftt);
//ignore this:
chart1.Series[0].Points.AddXY(i * 20, fft);
}
}
I got some ExcelValues, the fields are named from 700-751 and 800-851. Now, I want to get the results and store them.
for (int countDur = 0; countDur<= 51; countDur++)
{
string excelFieldMember = $"N7{countDur}";
string excelFieldNonMember = $"N8{countDur}";
}
An exception occurs, when the index countDur is less than 10 because the result for countDur = 0 is not 700, it is 70 then, and so on.
So I used
if(countDur < 10)
But I think there is a smarter way to reach this. I know there is a string.Format() method and because the fields are int values, I have a IoString() method where I can paste a parameter for this.
My question is, what do I have to paste in as a parameter? I can't find it in the C# documentation.
If the value is lower than 10, I want to have a 0 written before the index countDur gets pasted.
You want this:
for (int countDur = 0; countDur<= 51; countDur++)
{
string excelFieldMember = $"N7{countDur:D2}";
string excelFieldNonMember = $"N8{countDur:D2}";
}
This fills the number with trailing zeros, so that you get 700 instead of 70.
MSDN: The Decimal ("D") Format Specifier
Though you are looking for a way to use the ToString why not just start the for loop from the index you need, instead of from 0:
for (int countDur = 700; countDur <= 751; countDur++)
{
string excelFieldMember = $"N{countDur}";
string excelFieldNonMember = $"N{countDur+100}";
}
In any case, the use of "magic numbers" is prone to bugs if the fields change. See how you can get the value rather than have it stored hard-coded for the loop. (Same goes for the +100 for the non-member fields)
Try this, I think it's what you need
string excelFieldMember = $"N7{countDur.ToString("D2")}";
string excelFieldNonMember = $"N8{countDur.ToString("D2")}";
I'm making a program which reverses words to sdrow.
I understand that for it to work it needs to be written this way.
I'm more interested on WHY it has to be this way.
Here is my code:
Console.WriteLine("Enter a word : ");
string word = Console.ReadLine();
string rev = "";
int length;
for (length = word.Length - 1; length >= 0; length--)
{
rev = rev + word[length];
}
Console.WriteLine("The reversed word is : {0}", rev);
My questions are:
a) why you must use quotes to initialize your string
b) Why must you start your loop at one less than the total length of your string
c) How arrayname[int] works
I'm pretty new to C# and this site, as well. I hope my questions make sense and that I've asked them in the correct and proper way.
Thank you for your time!
This is how I've interpreted your question.
You want to know why you must use quotes to initialize your string
Why must you start your loop at one less than the total length of your string
How arrayname[int] works
I think that the best way to explain this to you is to go through your code, and explain what it does.
Console.WriteLine("Enter a word : ");
The first line of code prints Enter a word : into the console.
string word = Console.ReadLine();
This line "reads" the input from the console, and puts it into a string called word.
string rev = "";
This initiates a string called rev, setting it's value to "", or an empty string. The other way to initiate the string would be this:
string rev;
That would initiate a string called rev to the value of null. This does not work for your program because rev = rev + word[length]; sets rev to itself + word[length]. It throws an error if it is null.
The next line of your code is:
int length;
That sets an int (which in real life we call an integer, basically a number) to the value of null. That is okay, because it gets set later on without referencing itself.
The next line is a for loop:
for (length = word.Length - 1; length >= 0; length--)
This loop sets an internal variable called length to the current value of word.Length -1. The second item tells how long to run the loop. While the value of length is more than, or equal to 0, the loop will continue to run. The third item generally sets the rate of increase or decrease of your variable. In this case, it is length-- that decreases length by one each time the loop runs.
The next relevant line of code is his:
rev = rev + word[length];
This, as I said before sets rev as itself + the string word at the index of length, whatever number that is at the time.
At the first run through the for loop, rev is set to itself (an empty string), plus the word at the index of length - 1. If the word entered was come (for example), the index 0 would be c, the index 1 would be o, 2 would be m, and 3 = e.
The word length is 4, so that minus one is 3 (yay - back to Kindergarten), which is the last letter in the word.
The second time through the loop, length will be 2, so rev will be itself (e) plus index 2, which is m. This repeats until length hits -1, at which point the loop does not run, and you go on to the next line of code.
...Which is:
Console.WriteLine("The reversed word is : {0}", rev);
This prints a line to the console, saying The reversed word is : <insert value of rev here> The {0} is an internal var set by the stuff after the comma, which in this case would be rev.
The final output of the program, if you inserted come, would look something like this:
>Enter a word :
>come
>
>The reversed word is : emoc
a) you must to initialize or instantiate the variable in order to can work with it. In your case is better to use and StringBuilder, the string are inmutable objects, so each assignement means to recreate a new string.
b) The arrays in C# are zero index based so their indexes go from zero to length -1.
c) An string is an characters array.
Any case maybe you must to try the StringBuilder, it is pretty easy to use
I hope this helps
a) you need to initialize a variable if you want to use it in an assignment rev = rev + word[length];
b) you are using a for loop which means that you define a start number length = word.Length - 1, a stop criteria length >= 0 and a variable change length--
So lenght basically descends from 5 to 0 (makes 6 loops). The reason is that Arrays like 'string' a char[] are zerobased indexed.. means that first element is 0 last is array.Length - 1
c) So a string is basically a chain of char's.. with the []-Operator you can access a single index. The Return Type of words[index] is in this case a character.
I hope it helped
a) You need to first instantiate the string rev before you can assign it values in the loop. You could also say "string rev = String.Empty". You are trying to add word to rev and if you don't tell it first that rev is an empty string it doesn't know what it is adding word to.
b) The characters of the string have indexes to show which position they appear in the string. These indexes start at 0. So you're first character will have an index of 0. If the length of your string is 6 then the last character's index will be 5. So length - 1 will give you the value of the last character's index which is 5. A c# for loop uses the following parameters
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
where "int i = 0;" is the starting index; "i < 10" tells the loop when to stop looping; and "i++" tells it to increment i (the index) after each loop.
So in your code you are saying start at the last character of my string; perform this loop while there are still characters in the string; and decrease the index of the string after each loop so the next loop will look at the previous character in the string.
c) word[length] then in this scenario is saying add the character that has the position with index "length" to the rev string. This will basically reverse the word.
As usual you can do it in linq and avoid the (explicit) loops
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a word : ");
string word = Console.ReadLine();
Console.WriteLine("The reversed word is : {0}", new string (word.Reverse().ToArray()));
Console.ReadLine();
}
}
}
var reversedWords = string.Join(" ",
str.Split(' ')
.Select(x => new String(x.Reverse().ToArray())));
Take a look here :
Easy way to reverse each word in a sentence
I am attempting to take numbers (characters 0-9) in from a file and store them in memory.
Lets say we have a string called "register" (and can only (must) hold 5 chars max) and the register string will take in numbers that are read from the file so for example:
File1.txt:
The house number is 10 and the price is 4000 and 3.
So the register would be filled with the following: "10400"
Some logic would then be performed against the string and then the first char would be removed from string and everything would shift 1 to the left and another char (number) from the file would be added e.g.:
04000
and then...
40003
Hopefully somebody could shed some light on this and provide some ways of achieving this :)
Well, if you want to lop the first character off a string and add on one at the end, you can just say:
string s = "10400";
string t = s.Substring(1) + "0";
This gives t = "04000". Repeating:
string u = t.Substring(1) + "3";
This gives u = "40003".
So, what more do you want? Figuring out the logic of what to add to the end is your job.
OK...
First, a FileStream and associated StreamReaders will allow you to read from the file in pretty much any format you desire. This will be important because your specific algorithm will determine the retrieval method.
Boiling it down, you want to read characters from the file, and when that character is a number, store it in the register, continuing in this manner until you have five number characters in the register. Then, you'll do some logic that results in the first number no longer being useful, so you truncate it and get the next value.
How about something along these lines?
var register = new StringBuilder();
using(var stream = File.Open("File1.txt"))
{
bool ended, fileEnded;
int buffer;
while(!ended)
{
while(register.Length < 5 && !fileEnded)
{
buffer = stream.ReadByte();
if(buffer == -1)
{
fileEnded = true;
break;
}
var myChar = (char)buffer;
if(Char.IsNumber(myChar))
StringBuilder.Append(myChar);
}
//at this point you have 5 characters in register (or have run out of file).
//perform your logic, then remove the front character
register.Remove(0,1);
//repeat the loop. You won't get any more new characters once you reach the end of file,
//but the main loop will keep running until you set ended to true
if(WereDone())
ended=true;
}
stream.Close();
}
You could also read the entire file into a string variable, then apply a Regex that will find number characters, concatenate those into a large buffer, then fill your Register from that. That is a better approach for a small file, but this one will work for any file size.
You can create an extension method to List like so:
static class Helper
{
public static void Push<T>(this List<T> list, T item)
{
if (list.Count == 5)
list.RemoveAt(0);
list.Add(item);
}
}
And then you can use it like:
List<char> queue = new List<char>(5);
queue.Push('1');
queue.Push('0');
queue.Push('4');
queue.Push('0');
queue.Push('0');
Subsequent Call to Push will remove the first char and add the last
queue.Push('1');
I would likely put a method for fetching the correct string into a value. See below for an example:
static string FetchRegister(string Source, int Max, int StartIndex)
{
string Register = string.Empty;
int RegisterIndex = 0;
for (int i = 0; i < Source.Length; i++)
{
if (char.IsNumber(Source[i]))
{
if (RegisterIndex >= StartIndex)
{
Register += Source[i].ToString();
if (Register.Length == Max)
{
return Register;
}
}
RegisterIndex += 1;
}
}
return Register;
}
Well, I've tried it with ToInt, ToString, and I'm out of options.
I'm trying to substract 2 Label Texts from each other. (Those contains numbers from RSS)
What I have at the moment:
lblOldID.Text = nodeChannel["oldid"].InnerText;
lblNewID.Text = nodeChannel["newid"].InnerText;
So let's say oldid contains "500" and newid "530".
But for some reason, I can't substract (-) them.
What I want:
lblResultID.Text = lblOldID.Text - lblNewID.Text;
Example: Result = 530 - 500
So how is that possible?
You need to convert the text to ints.
//These are the ints we are going to perform the calculation on
Int32 oldID = 0;
Int32 newID = 0;
//TryParse returns a bool if the string was converted to an int successfully
bool first = Int32.TryParse(lblOldID.Text, out oldID);
bool second = Int32.TryParse(lblNewID.Text, out newID);
//Check both were converted successfully and perform the calculation
if(first == true && second == true)
{
lblResultID.Text = (oldID - newID).ToString();
}
else
{
lblResultID.Text = "Could not convert to integers";
}
TryParse prevents an exception being thrown if the data in the labels cannot be converted to integers. Instead, it returns false (or true if the numbers were parsed successfully).
If you want the label text to be, literally, 530 - 500, concatenate the strings like so:
lblResultID.Text = lblOldID.Text + " - " + lblNewID.Text;
If you want the label text to be the result of subtracting the numbers represented in the labels, convert them to integers first:
int old = Int32.Parse(lblOldID.Text);
int new = Int32.Parse(lblNewID.Text);
lblResultID.Text = (old - new).ToString();
(You'll need some error checking in there if there's the possibility that either value might not convert cleanly to an integer)
Perhaps because you really should parse them:
lblResultID.Text = (int.Parse(lblOldID.Text) - int.Parse(lblNewID.Text)).ToString();
Or in string format:
lblResultID.Text = lblOldID.Text + " - "+ lblNewID.Text;