Passing string array to method and display result (WPF, C#) - c#

When I selected folder Im printing this path to my TextBlock (WPF):
folderName = dialog.SelectedPath.ToString();
tbArea = "Selected Path: " + dialog.SelectedPath.ToString() + "\r\n";
As probably I will use this more then one time, I have created method:
public void addToTextArea(string[] newString)
{
tbArea = tbArea + newString + "\r\n";
}
Now Im doing like this:
string[] arr = {"Selected Path", dialog.SelectedPath.ToString()};
addToTextArea(arr);
But as result Im getting this: System.String[].
What is wrong or missing?

If you want to join items in an array with some common string in between them, you can use the string.Join method (note I'm using Environment.NewLine instead of \r\n because it's more platform-friendly):
public void AddToTextArea(string[] newStrings)
{
tbArea += string.Join(Environment.NewLine, newStrings) + Environment.NewLine;
}
The string.Join method takes in a string to conacatenate the items with and then returns a string containing all the items joined with the specified string. A more common example is:
int[] items = {1,2,3,4,5};
Console.WriteLine(string.Join(", ", items));
// Output: "1, 2, 3, 4, 5"
Note that there is no leading or trailing connecting string (", ") added to the list, so in your case we add a newline character to the end.
An alternative would be to create an overload that takes in a single string, and then call that method for each item in the string array:
public void AddToTextArea(string[] newStrings)
{
foreach (string newString in newStrings)
{
AddToTextArea(newString);
}
}
public void AddToTextArea(string newString)
{
tbArea = tbArea + newString + Environment.NewLine;
}

Related

Split and Append "AND" between values

how to split below value and append AND between values ?
I cannot Split with Space as there is spaces between words
"\"Mark John\" \"Tina Roy\""
as
"\"Mark John\" AND \"Tina Roy\""
In the end it should look like -
"Mark John" AND "Tina Roy"
Any help is appreciated.
string operatorValue = " AND ";
if (!string.IsNullOrEmpty(operatorValue))
{
foreach (string searchVal in SearchRequest.Text.Split(' '))
{
if (!string.IsNullOrEmpty(searchVal))
searchValue += searchVal + operatorValue;
}
}
int index = searchValue.LastIndexOf(operatorValue);
if (index != -1)
{
outputSearchValue = searchValue.Substring(0, index);
}
Try
var result = str.Replace("\" \"","\" And \"");
If you have more than one name, or there is a possibility that you could have more than one whitespace between two names, you could opt for Regex.
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Example,
var str = "\"Mark John\" \"Tina Roy\" \"Anu Viswan\"";
var result = Regex.Replace(str,"\"\\s+\"","\" And \"");
Output
"Mark John" And "Tina Roy" And "Anu Viswan"
Or use Regular Expressions:
var test = "\"John Smith\" \"Bill jones\" \"Bob Norman\"";
Console.WriteLine(Regex.Replace(test, "\" \"", "\" AND \""));
Instead of splitting, replace the " " with " AND "
var test = "\"Mark John\" \"Tina Roy\"";
var new_string= test.Replace("\" \"", " AND ");

Replace closest instance of a word

I have a string like this:
“I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”
I want to insert <strong> around the "a" in "a diplomatic", but nowhere else.
What I have as input is diplomatic from a previous function, and I wan't to add <strong>to the closest instance of "a".
Right now, of course when I use .Replace("a", "<strong>a</strong>"), every single instance of "a" receives the <strong>-treatment, but is there any way to apply this to just to one I want?
Edit
The string and word/char ("a" in the case above) could be anything, as I'm looping through a lot of these, so the solution has to be dynamic.
var stringyourusing = "";
var letter = "";
var regex = new Regex(Regex.Escape(letter));
var newText = regex.Replace(stringyourusing , "<strong>letter</strong>", 1);
Would this suffice?
string MakeStrongBefore(string strong, string before, string s)
{
return s.Replace(strong + " " + subject, "<strong>" + strong + "</strong> " + before);
}
Used like this:
string s = “I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.”;
string bolded = MakeStrongBefore("a", "diplomatic", s);
Try this:
public string BoldBeforeString(string source, string bolded,
int boldBeforePosition)
{
string beforeSelected = source.Substring(0, boldBeforePosition).TrimEnd();
int testedWordStartIndex = beforeSelected.LastIndexOf(' ') + 1;
string boldedString;
if (beforeSelected.Substring(testedWordStartIndex).Equals(bolded))
{
boldedString = source.Substring(0, testedWordStartIndex) +
"<strong>" + bolded + "</strong>" +
source.Substring(testedWordStartIndex + bolded.Length);
}
else
{
boldedString = source;
}
return boldedString;
}
string phrase = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
string boldedPhrase = BoldBeforeString(phrase, "a", 41);
Hei!
I've tested this and it works:
String replaced = Regex.Replace(
"I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.",
#"(a) diplomatic",
match => "<strong>" + match.Result("$1") + "</strong>");
So to make it a general function:
public static String StrongReplace(String sentence, String toStrong, String wordAfterStrong)
{
return Regex.Replace(
sentence,
#"("+Regex.Escape(toStrong)+") " + Regex.Escape(wordAfterStrong),
match => "<strong>" + match.Result("$1") + "</strong>");
}
Usage:
String sentence = "I’m a member of the Imperial Senate on a diplomatic mission to Alderaan.";
String replaced = StrongReplace(sentence, "a", "diplomatic");
edit:
considering your other comments, this is a function for placing strong tags around each word surrounding the search word:
public static String StrongReplace(String sentence, String word)
{
return Regex.Replace(
sentence,
#"(\w+) " + Regex.Escape(word) + #" (\w+)",
match => "<strong>" + match.Result("$1") + "</strong> " + word + " <strong>" + match.Result("$2") + "</strong>");
}

How to loop through properties of objects in c#?

I have a method which gets the values of the properties of an object and appends some commas to it. I want to make this generinc so i can use it with other objects.
foreach (var row in rows.ToList())
{
sbResult.Append(
delimiter + row.MediaName + delimiter + separator +
delimiter + row.CountryName + delimiter + separator +
delimiter + row.ItemOverRideDate + delimiter + separator +
delimiter + row.Rating + delimiter + separator +
delimiter + row.BatchNo + delimiter + separator +
delimiter + row.NoInBatch + delimiter + separator +
delimiter + row.BatchDate + delimiter + separator +
delimiter + row.DataType + delimiter + separator +
delimiter + row.ByLine + delimiter + separator +
delimiter + row.IssueNo + delimiter + separator +
delimiter + row.Issue + delimiter + separator +
delimiter + row.MessageNo + delimiter + separator +
delimiter + row.Message + delimiter + separator +
delimiter + row.SourceName + delimiter + separator +
delimiter + row.SourceType + delimiter + separator);
//end of each row
sbResult.AppendLine();
}
I have tried using var rowData = row.GetType().GetProperties(); but it only returns the property itself and I dont know how to get the value of the property.
Since Type.GetProperties returns a collection of PropertyInfo, you follow that up by calling PropertyInfo.GetValue. Here's how you can do that (and all the rest together) with LINQ:
var line = string.Join(
row.GetType().GetProperties()
.Select(pi => pi.GetValue(row))
.Select(v => delimiter + v.ToString() + delimiter),
separator);
However, you might want to reconsider your approach. This code will break if GetProperties fetches static properties or indexers along with "normal" properties; it also requires that the code be run with full trust (otherwise no reflection is possible). And finally, it's going to be slow because a) reflection is inherently slow and b) it will keep reflecting on the same things over and over again without caching any of the information it has already discovered.
In addition to the above potential problems, if there is even a remote chance that you will later want to filter what gets printed out it is probably better to encapsulate this logic inside a (virtual?) method on row and just do something like
sbResult.AppendLine(row.SerializeAsLine());
You can use something like this to iterate over all the properties of a particular type:
public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(T)
select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}
Then you could specify the type as string for all your string properties.
Compilable sample:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
private static void Main()
{
var test = new Test
{
Str1 = "S1",
Str2 = "S2",
Str3 = "S3",
Str4 = "S4"
};
foreach (var property in PropertiesOfType<string>(test))
{
Console.WriteLine(property.Key + ": " + property.Value);
}
}
public static IEnumerable<KeyValuePair<string, T>> PropertiesOfType<T>(object obj)
{
return from p in obj.GetType().GetProperties()
where p.PropertyType == typeof(T)
select new KeyValuePair<string, T>(p.Name, (T)p.GetValue(obj));
}
}
public class Test
{
public string Str1 { get; set; }
public string Str2 { get; set; }
public string Str3 { get; set; }
public string Str4 { get; set; }
}
}
Here it is.
List<PropertyInfo> _propInfo = _row.GetType().GetProperties();
foreach (var item in _propInfo)
{
object _value = item.GetValue(_row, null);
if (_value != null)
{
// Save the Value
}
}
GetProperties returns an array of PropertyInfo, so use the GetValue method and use your object as it's input to get the value for each property. Here is the code:
public class MyClass
{
public string MyProperty1 { get; set; }
public string MyProperty2 { get; set; }
public string MyProperty3 { get; set; }
}
Then
MyClass myObj = new MyClass() { MyProperty1 = "first", MyProperty2 = "second", MyProperty3 = "third" };
List<string> array = new List<string>();
foreach (var item in typeof(MyClass).GetProperties())
{
array.Add(item.GetValue(myObj, null).ToString());
}
var result = string.Join(",", array); //use your own delimiter
var values = instance
.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Select(z => string.Format("{0}: {1}\n", z.Name, z.GetValue(instance, null)));
string res = string.Concat(values);
Where instance is the instance of your object. You might want to avoid LINQ and use a loop if StringBuilder is required (depending on the number of properties).

How to trim whitespace between characters

How to remove whitespaces between characters in c#?
Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".
But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?
You could use String.Replace method
string str = "C Sharp";
str = str.Replace(" ", "");
or if you want to remove all whitespace characters (space, tabs, line breaks...)
string str = "C Sharp";
str = Regex.Replace(str, #"\s", "");
If you want to keep one space between every word. You can do it this way as well:
string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));
Use String.Replace to replace all white space with nothing.
eg
string newString = myString.Replace(" ", "");
if you want to remove all spaces in one word:
input.Trim().Replace(" ","")
And If you want to remove extra spaces in the sentence, you should use below:
input.Trim().Replace(" +","")
the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.
If you want to keep one space between every word. this should do it..
public static string TrimSpacesBetweenString(string s)
{
var mystring =s.RemoveTandNs().Split(new string[] {" "}, StringSplitOptions.None);
string result = string.Empty;
foreach (var mstr in mystring)
{
var ss = mstr.Trim();
if (!string.IsNullOrEmpty(ss))
{
result = result + ss+" ";
}
}
return result.Trim();
}
it will remove the string in between the string
so if the input is
var s ="c sharp";
result will be "c sharp";
//Remove spaces from a string just using substring method and a for loop
static void Main(string[] args)
{
string businessName;
string newBusinessName = "";
int i;
Write("Enter a business name >>> ");
businessName = ReadLine();
for(i = 0; i < businessName.Length; i++)
{
if (businessName.Substring(i, 1) != " ")
{
newBusinessName += businessName.Substring(i, 1);
}
}
WriteLine("A cool web site name could be www.{0}.com", newBusinessName);
}
var str=" c sharp "; str = str.Trim();
str = Regex.Replace(str, #"\s+", " "); ///"c sharp"
string myString = "C Sharp".Replace(" ", "");
I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:
namespace XXX.Models
{
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductImage
{
get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
}
}
}
So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.

Adding a newline into a string in C#

I have a string.
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
I need to add a newline after every occurence of "#" symbol in the string.
My Output should be like this
fkdfdsfdflkdkfk#
dfsdfjk72388389#
kdkfkdfkkl#
jkdjkfjd#
jjjk#
Use Environment.NewLine whenever you want in any string. An example:
string text = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
text = text.Replace("#", "#" + System.Environment.NewLine);
You can add a new line character after the # symbol like so:
string newString = oldString.Replace("#", "#\n");
You can also use the NewLine property in the Environment Class (I think it is Environment).
The previous answers come close, but to meet the actual requirement that the # symbol stay close, you'd want that to be str.Replace("#", "#" + System.Environment.NewLine). That will keep the # symbol and add the appropriate newline character(s) for the current platform.
Then just modify the previous answers to:
Console.Write(strToProcess.Replace("#", "#" + Environment.NewLine));
If you don't want the newlines in the text file, then don't preserve it.
A simple string replace will do the job. Take a look at the example program below:
using System;
namespace NewLineThingy
{
class Program
{
static void Main(string[] args)
{
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", "#" + Environment.NewLine);
Console.WriteLine(str);
Console.ReadKey();
}
}
}
as others have said new line char will give you a new line in a text file in windows.
try the following:
using System;
using System.IO;
static class Program
{
static void Main()
{
WriteToFile
(
#"C:\test.txt",
"fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#",
"#"
);
/*
output in test.txt in windows =
fkdfdsfdflkdkfk#
dfsdfjk72388389#
kdkfkdfkkl#
jkdjkfjd#
jjjk#
*/
}
public static void WriteToFile(string filename, string text, string newLineDelim)
{
bool equal = Environment.NewLine == "\r\n";
//Environment.NewLine == \r\n = True
Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);
//replace newLineDelim with newLineDelim + a new line
//trim to get rid of any new lines chars at the end of the file
string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();
using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
{
sw.Write(filetext);
}
}
}
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
var result = strToProcess.Replace("#", "# \r\n");
Console.WriteLine(result);
Output
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", Environment.NewLine);
richTextBox1.Text = str;
Based on your replies to everyone else, something like this is what you're looking for.
string file = #"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
string[] lines = strToProcess.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
using (StreamWriter writer = new StreamWriter(file))
{
foreach (string line in lines)
{
writer.WriteLine(line + "#");
}
}
Change your string as mentioned below.
string strToProcess = "fkdfdsfdflkdkfk"+ System.Environment.NewLine +" dfsdfjk72388389"+ System.Environment.NewLine +"kdkfkdfkkl"+ System.Environment.NewLine +"jkdjkfjd"+ System.Environment.NewLine +"jjjk"+ System.Environment.NewLine;
You could also use string[] something = text.Split('#'). Make sure you use single quotes to surround the "#" to store it as a char type.
This will store the characters up to and including each "#" as individual words in the array. You can then output each (element + System.Environment.NewLine) using a for loop or write it to a text file using System.IO.File.WriteAllLines([file path + name and extension], [array name]). If the specified file doesn't exist in that location it will be automatically created.
protected void Button1_Click(object sender, EventArgs e)
{
string str = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
str = str.Replace("#", "#" + "<br/>");
Response.Write(str);
}
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string strToProcess = "fkdfdsfdflkdkfk#dfsdfjk72388389#kdkfkdfkkl#jkdjkfjd#jjjk#";
strToProcess.Replace("#", Environment.NewLine);
Console.WriteLine(strToProcess);
}
}

Categories

Resources