Click here to Skip to main content
15,914,642 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I used the following code but when i write for example " my name is asmaa "
the result :"my ne asmaa"
why name convert to ne?



using (TextWriter tw = new StreamWriter(@"D:\output.txt"))
{
using (StreamReader reader = new StreamReader("D:\\input.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
string[] stopWord = new string[] { "is", "are", "am", "could", "will" , "in" };
foreach (string word in stopWord)
{
line = line.Replace(word, "");

}
tw.Write(line);
}
}
}
Posted
Comments
[no name] 20-Mar-13 21:02pm    
Because you are replacing, line.Replace(word, ""), the "am" from the stopWord array, in name and then writing the "ne" back to the output file?
Sergey Alexandrovich Kryukov 21-Mar-13 0:46am    
5! :-)
Sergey Alexandrovich Kryukov 21-Mar-13 0:48am    
The question makes very little sense. It's quite apparent why you got what you got, but there was no a need to ask this question.
Did you ever use the debugger?
—SA

1 solution

It's doing exactly what you told it to: replace all instances of those strings with nothing. You haven't specified in anyway that you mean only whole words. What you'll want to use here is regular expressions[^]. In this case, what will be of specific interest to you is the special group "\b", which is word boundary. For example, using the regular expression "\bam\b" will only match "am" if it isn't part of another word (note, this will however match in some cases where there is not a space before and after, like if it appears at the beginning or end of a string, or before or after punctuiation, like "am.", but I'm guessing you want that).

In C#, regular expressions can be used with the Regex[^] class.

For example:
C#
line = Regex.Replace(line, @"\bam\b", "");


will replace "am" in line with an empty string. (And, in case you haven't seen it before, the @ before the string specifies that the escape character, \, will just be treated as itself, which is helpful when writing regular expressions, otherwise the example would become "\\bam\\b", and can start to become more difficult to read in more complicated patterns.)
 
Share this answer
 
Comments
Member 10561362 22-Mar-14 21:18pm    
It works

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900