Replacing string in a list doesn't work [duplicate] - c#

This question already has answers here:
Why does the Replace() string method not modify my string variable?
(4 answers)
Closed 9 years ago.
I cannot, for the life of me, understand why the Replace(); method will not work when I try to replace the text of an element inside a list of type String. This question is, to an extent, related to a previous thread of mine [found here: Merging two files and handling duplicate entries (would be a good idea to view it, as well, for the full code)], but at the end of the day, it all boils down to the fact that the command doesn't work while, my code, is actually correct (!).
I'll give you an example of what doesn't work in my situation. In its most basic form, for the sake of example, this is what I'm trying to accomplish but it doesn't work (for real!):
[In my original code, I've triple-checked (with breakpoints and everything) that my list indeed contains the string I want to replace (I'm replacing the element itself!), but it just won't do it! Seriously now, it is a 4 element list at the present time (although more elements CAN be added, refer to other thread).]
One last thing, sorry about the punctuation (too many exclamation marks, I know), but I'm actually raging over this. Code below (remember, most basic form, but an example I tried):
// List[index].Replace(oldValue, newValue);
newFile[3].Replace(newFile[3], "Replace it with this!");
Could you help me with this?

newFile[3] = newFile[3].Replace(newFile[3], "Replace it with this!");
In c#, strings are immutable. As such, the Replace method returns a new string.
Edit:
The main reason for strings to be immutable is to make them thread-safe.
If you wanna find out more, have a read: Why .NET String is immutable?

newFile[3] = newFile[3].Replace(newFile[3], "Replace it with this!");

Related

Template class names in weird forms (.NET)

I'm retrieving the names of all the classes in the current runtime in .NET, for the purpose of identifying object and function declarations in sourcecode that's given as input to my program, but templates seem a bit off, for example I've got this among the output:
hashset`1+elementcount[t]
hashset`1+slot[t]
hashset`1+enumerator[t]
which I obtain more or less from this simple code (there's some similar code that gets the referenced assemblies but essentially does the following for each of those instead of the executing assembly).
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
types.Add(t.ToString().Split('.').Last().ToLower());
}
For now I can of course just Split() the strings to get the first part, before the ` mark, but I was wondering if anyone knows exactly what this might be. The three lines above are consecutive, and a couple more entries for HashSet in my results also have this 1+something thing, so I'm positive it's the actual HashSet class. (note: I'm turning everything to lowercase currently but disabling it doesn't seem to change anything.)
So... anyone know what's this notation? Not sure how to google it, but copy-pasting some lines to Google and enclosing in quotes returns either no results or very random threads that don't end up having the line in them. Thanks in advance.

Removing block of code from class if condition is met [duplicate]

This question already has answers here:
How to delete a line from a text file in C#?
(11 answers)
Closed 10 years ago.
What I'm doing is reading a file line by line, and then comparing each line that's read with a pre-specified string. If it's a match, I want to remove the code from the class I'm inspecting, starting at the line that matched the pre-specified string until a designated location I've identified is reached. What I'm struggling with is how to implement a removal. I've written methods to add, subtract, adjust, etc., but never to just completely remove a chunk of code, so I don't know how to procede. I bet there's some simple way to accomplish this, but it's escaping me right now.
It sounds like you are asking "How do I remove something from the middle of a file?" - it just happens to be source code.
The easiest way is to create a temp file (or in memory stream) to which you write all the content you want to keep and then when you are done processing the old file you over-write it with the contents you choose to keep.

To find out the number of occruence of words in a file

I came across this question in an interview:
We have to find out the number of occurences of two given words in a text file with <=n words between them.
Example1:
text:`this is first string this is second string`
Keywords:`this, string`
n= 4
output= 2
"this is first string" is the first occurrence and number of words between this and string is 2(is, first) which is less than 4.
this is second string is the remaining string. number of words between *this and string * is 2 (is, second) which is less than 4.
Therefore the answer is 2.
I have thought that I will use
Dictionary<string, List<int>>.
My idea was that I use the dictionary and get the list of places where the particular word is repeated and then iterate through both the lists, increment the count if a condition is met and then display the count.
Is my thinking process correct? Please provide any suggestions to improve my solution.
Thanks,
Not an answer per-se (as quite honestly, I don't understand the question :P), but to add some general interview advice to the other answers:
In interviews the interviewer is always looking for the thought process and that you are a critical, logical thinker. Not necessarily that you have excellent coding recall and can compile code in your brain.
In addition interviews are a stressful process. By slowing down and talking out loud as you work things out you not only look like a better communicator and logical thinker (even if getting the question wrong), you also give yourself time to think.
Use a pen and paper, speak as you think, start off from the top and work through it. I've got jobs even if I didn't know the answers to tech questions by demonstrating that I can at least try to work things out ;-)
In short, it's not just down to technical prowess
I think it depends if the call is done only one or multiple times per string. If it's something like
int getOccurences(String str, String reference, int min_size) { ... }
then you don't really need the dictionary, not even a ist. You can just iterate through the string to find occurrences of words and then check the number of separators between them.
If on the other hand the problem is for arbitrary search/indexing, IMHO you do need a dictionary. I'd go for a dictionary where the key is the word and the value is a list of indexes where it occurs.
HTH
If you need to do that repeatedly for different pairs of words in the same text, then a word dictionary with a list of indexes is a good solution. However, if you were only looking for one pair, then two lists of indexes for those two words would be sufficient.
The lists allow you to separate the word detection operation from the counting logic.

Return number as text [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I convert an integer into its verbal representation?
I am looking for some solution to return a number as text.
By that I mean that 100 should be returned as 'one hundred'
It is more or less just a tidious task to make such a function myself, but I rather not re-invent the wheel, and this can't be the first time someones has requested this.
Unfortunatly my search so far has not turned up anything, so here I try stackowerflow.
Basically the numbers comes from a database, so if there is some smart methods you could use here it would be pretty nice.
As mentioned, a small function that returns eg. 100 as 'one hundred' is not a complicated task, but what if you need to take language considarations into the solution?
Has anybody come accross something that actually can do this, and perhaps in multiple languages?
Yes you can use this:
Java numbers to text
Basically the idea is to form the numbers by simply defining all the digits and the tenths, and after that you can also the define the hundreds, the thousands and so on. Because numbers in English are always formed the same way, this is very easy for the English language.
Something like this (may be not the best one, I just make a draft search)?
http://www.daniweb.com/software-development/csharp/threads/53072

Follow up: How do get some of the object from a list without Linq?

I have a question about this question. I posted a reply there but since it's been marked as answered, I don't think I'll get a response to my post there.
I am running C# framework 2.0 and I
would like to get some of the data
from a list? The list is a List<>. How
can I do that without looping and
doing comparaison manually on each
element of the List<>?
It really looks like the answers are just a more elegant ways of comparing every element of the List. Given that the list is not guaranteed to be sorted prior to the search, do any of the methods provided in the original post ensure that they are looking at a smaller subset of the original list?
EDIT: One thing to note is that I'm not trying to do anything here. I just want to know if the solutions provided in another question truly do what the OP asked, with regards to looping through the whole list. In general, to search an unsorted list (at least it's not required given the data structure), you will have to search the entire list. However, do any of the solutions on the other thread have an underlying optimization to prevent searching the entire list?
EDIT: I really didn't get any answers that were all that helpful but I will give credit to the answer that at least confirmed my common sense belief. If I notice a new answer that is better, I will change my vote.
If your requirement is to find things quickly in an arbitrary collection, then perhaps a list isn't the best data structure for the job. :)
You might want to check out LINQ support for .Net 2.0.
Has explain in the thread your mentionned you can get some of the object from the list without LINQ.
list = list.FindAll(yourFilterCriteria);
The object yourFilterCriteria is a Predicate and can do comparison with all Property or Function in your object so it's very customizable.
Predicate<SimpleObject> yourFilterCriteria = delegate(SimpleObject simpleObject)
{
return simpleObject.FirstName.Contains("Skeet") && simpleObject.Age < 30;
};
This example show you that you can search the list without looping manullay and you will get all people with the First Name Skeet and Age under 30.
If you're only looking for the first match, then the Find method will do the job. It won't loop through the entire list, rather it will return the first occurrence of the object. However, if you want to find all of them, how exactly do you expect to search through only a subset of the data if it isn't sorted?

Categories

Resources