looking for best way for string manipulation - c#

I m looking for for some best way for string manipulation. Below is the expacted output,
[System/EventID=100 or System/EventID=108], commutative string should starts with [ and end with ] plus has to remove extra or in between?
try
{
string systemEvents = string.Empty;
var eventIds = "100,108".Split(',');
systemEvents += "[";
foreach (var eventId in eventIds)
{
systemEvents += "System/EventID=" + eventId + " or ";
}
var X = systemEvents.Remove(systemEvents.Length - 4).Trim();
var Y = X + "]";
}
catch (Exception ex)
{
throw ex;
}

You can make use of available string handling functions like String.Format()(which replace specified format items with the text representation of the corresponding object values.) and String.Join()(Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string.) to do this work. Try the following snippet, also Check a Working Example Here
string eventIdStr = String.Join(" or ", eventIds.Select(x=> "System/EventID=" +x))
string systemEvents = String.Format("[{0}]",eventIdStr);

var s = string.Format("[{0}]", string.Join(" or ", "100,108".Split(',').Select(x=> "System/EventID=" + x));

Related

Change special chars in string

I am using c# and in code from appsettings.json I take strings and convert them if special chars exists. this is my code
int? a = applicationRequestViewModel.GetApplicantIndex();
int? g = applicationRequestViewModel.GetGurantorIndex();
foreach (var keys in _options.Value.RegisterParamKeys)
{
string value = keys.Split(";")[0];
string name = keys.Split(";")[1];
string key = value.Split(":")[typeOfApplicant];
key = Regex.Replace(key, #"[^\[a\]]", "[" + a + "]");
key = Regex.Replace(key, #"[^\[g\]]", "[" + g + "]");
var registrationProperty = new RegistrationProperty() { };
registrationProperty.Name = name;
registrationProperty.Value = (string)rss.SelectToken(key);
listOfRegistrationProperty.Add(registrationProperty);
}
from appsettings.json I took below strings
"RegisterBatchParams": [
"applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber:applicationInfo.applicationNumber;applicationNumber",
"applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType:applicationInfo.applicantType;applicantType",
"applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment:applicationInfo.customerSegment;customerSegment",
"applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText:applicationInfo.applicationStatusLocalText;applicationStatus",
"applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName:applicationRequestViewModel.applicants[a].businessPartner.person.firstName;customerName"
],
for the last string I want to change "applicants[a]" to with index number but it doesn't convert as expected how can I convert correctly?
As expected result
applicationRequestViewModel.applicants[0].businessPartner.person.firstName
but given result
a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0]a[0][0][0][0][0]a[0][0][0][0][0][0][0][0][0][0]
Instead of #"[^\[a\]]" use #"\[a\]".
But you don't even need regex for this. Simple string.Replace will do the job just as well.
Or, you can try this regex and replace only char inside of parentheses.
[a](?=[]])

Passing string array to method and display result (WPF, 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;
}

String: replace last ".something" in a string?

I have some string and I would like to replace the last .something with a new string. As example:
string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new
So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.
I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?
string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);
Output:
blabla.test.bla.text.new
ChangeExtension should work as advertised;
string replace = ".new";
string file = "testfile_this.00001...csv";
file = Path.ChangeExtension(file, replace);
>> testfile_this.00001...new
You can use string.LastIndexOf('.');
string replace = ".new";
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
string newString = test.Substring(0, pos-1) + replace;
of course some checking is required to be sure that LastIndexOf finds the final point.
However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;
No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.
string replace = ".new";
string input = "blabla.bla.test.jpg";
string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"
Please use this function.
public string ReplaceStirng(string originalSting, string replacedString)
{
try
{
List<string> subString = originalSting.Split('.').ToList();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < subString.Count - 1; i++)
{
stringBuilder.Append(subString[i]);
}
stringBuilder.Append(replacedString);
return stringBuilder.ToString();
}
catch (Exception ex)
{
if (log.IsErrorEnabled)
log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
throw;
}
}

SSIS Script Component: Microsoft.SqlServer.Dts.Pipeline.BlobColumn

Struggling with a C# Component. What I am trying to do is take a column that is ntext in my input source which is delimited with pipes, and then write the array to a text file. When I run my component my output looks like this:
DealerID,StockNumber,Option
161552,P1427,Microsoft.SqlServer.Dts.Pipeline.BlobColumn
Ive been working with the GetBlobData method and im struggling with it. Any help with be greatly appreciated! Here is the full script:
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string vehicleoptionsdelimited = Row.Options.ToString();
//string OptionBlob = Row.Options.GetBlobData(int ;
//string vehicleoptionsdelimited = System.Text.Encoding.GetEncoding(Row.Options.ColumnInfo.CodePage).GetChars(OptionBlob);
string[] option = vehicleoptionsdelimited.Split('|');
string path = #"C:\Users\User\Desktop\Local_DS_CSVs\";
string[] headerline =
{
"DealerID" + "," + "StockNumber" + "," + "Option"
};
System.IO.File.WriteAllLines(path + "OptionInput.txt", headerline);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + "OptionInput.txt", true))
{
foreach (string s in option)
{
file.WriteLine(Row.DealerID.ToString() + "," + Row.StockNumber.ToString() + "," + s);
}
}
Try using
BlobToString(Row.Options)
using this function:
private string BlobToString(BlobColumn blob)
{
string result = "";
try
{
if (blob != null)
{
result = System.Text.Encoding.Unicode.GetString(blob.GetBlobData(0, Convert.ToInt32(blob.Length)));
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
Adapted from:
http://mscrmtech.com/201001257/converting-microsoftsqlserverdtspipelineblobcolumn-to-string-in-ssis-using-c
Another very easy solution to this problem, because it is a total PITA, is to route the error output to a derived column component and cast your blob data to a to a STR or WSTR as a new column.
Route the output of that to your script component and the data will come in as an additional column on the pipeline ready for you to parse.
This will probably only work if your data is less than 8000 characters long.

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.

Categories

Resources