I have this string:
value1*value2*value3*value4
How would cut the String in multiple Strings?
string1 = value1;
string2 = value2;
etc...
My way (and probably not a very good way):
I take an array with all the indexes of the "*" character and after that, I call the subString method to get what I need.
string valueString = "value1*value2*value3*value4";
var strings = valueString.Split('*');
string string1 = strings[0];
string string2 = strings[1];
...
More info here.
Try this
string string1 = "value1*value2*value3*value4";
var myStrings = string1.Split('*');
string s = "value1*value2*value3*value4";
string[] array = s.Split('*');
simply :
string[] parts = myString.Split("*");
parts will be an array of string (string[])
you can just use the Split() method of the String-Object like so:
String temp = "value1*value2*value3*value4";
var result = temp.Split(new char[] {'*'});
The result variable is a string[] with the four values.
If you want to shine in society, you can also use dynamic code :
using System;
using System.Dynamic;
namespace ConsoleApplication1
{
class DynamicParts : System.Dynamic.DynamicObject
{
private string[] m_Values;
public DynamicParts(string values)
{
this.m_Values = values.Split('*');
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var index = Convert.ToInt32(binder.Name.Replace("Value", ""));
result = m_Values[index - 1];
return true;
}
public static void Main()
{
dynamic d = new DynamicParts("value1*value2*value3*value4");
Console.WriteLine(d.Value1);
Console.WriteLine(d.Value2);
Console.WriteLine(d.Value3);
Console.WriteLine(d.Value4);
Console.ReadLine();
}
}
}
Related
I'm trying to find a cleaner way of performing multiple sequential replacements on a single string where each replacement has a unique pattern and string replacement.
For example, if I have 3 pairs of patterns-substitutions strings:
1. /(?<!\\)\\n/, "\n"
2. /(\\)(?=[\;\:\,])/, ""
3. /(\\{2})/, "\\"
I want to apply regex replacement 1 on the original string, then apply 2 on the output of 1, and so on and so forth.
The following console program example does exactly what I want, but it has a lot of repetition, I am looking for a cleaner way to do the same thing.
SanitizeString
static public string SanitizeString(string param)
{
string retval = param;
//first replacement
Regex SanitizePattern = new Regex(#"([\\\;\:\,])");
retval = SanitizePattern.Replace(retval, #"\$1");
//second replacement
SanitizePattern = new Regex(#"\r\n?|\n");
retval = SanitizePattern.Replace(retval, #"\n");
return retval;
}
ParseCommands
static public string ParseCommands(string param)
{
string retval = param;
//first replacement
Regex SanitizePattern = new Regex(#"(?<!\\)\\n");
retval = SanitizePattern.Replace(retval, System.Environment.NewLine);
//second replacement
SanitizePattern = new Regex(#"(\\)(?=[\;\:\,])");
retval = SanitizePattern.Replace(retval, "");
//third replacement
SanitizePattern = new Regex(#"(\\{2})");
retval = SanitizePattern.Replace(retval, #"\");
return retval;
}
Main
using System;
using System.IO;
using System.Text.RegularExpressions;
...
static void Main(string[] args)
{
//read text that contains user input
string sampleText = File.ReadAllText(#"c:\sample.txt");
//sanitize input with certain rules
sampleText = SanitizeString(sampleText);
File.WriteAllText(#"c:\sanitized.txt", sampleText);
//parses escaped characters back into the original text
sampleText = ParseCommands(sampleText);
File.WriteAllText(#"c:\parsed_back.txt", sampleText);
}
Don't mind the file operations. I just used that as a quick way to visualize the actual output. In my program I'm going to use something different.
Here's one way:
var replacements = new List<(Regex regex, string replacement)>()
{
(new Regex(#"(?<!\\)\\n"), System.Environment.NewLine),
(new Regex(#"(\\)(?=[\;\:\,])"), ""),
(new Regex(#"(\\{2})"), #"\"),
};
(Ideally cache that in a static readonly field):
Then:
string retval = param;
foreach (var (regex, replacement) in replacements)
{
retval = regex.Replace(retval, replacement);
}
Or you could go down the linq route:
string retval = replacements
.Aggregate(param, (str, x) => x.regex.Replace(str, x.replacement));
I am trying to compare a string to see if it contains a curse word. I assumed that I could do this using str.Contains("" || "") although I quickly realized I cannot use || with two strings. What would I use in place of this?
str.Contains("123" || "abc");
I expected it to see if it contains 123 or abc but the code segment does not work as it cannot compare two strings.
var str = "testabc123";
var str2 = "helloworld";
var bannedWords = new List<string>
{
"test",
"ok",
"123"
};
var res = bannedWords.Any(x => str.Contains(x)); //true
var res2 = bannedWords.Any(x => str2.Contains(x)); //false
You can do something like this. Create a list with the swear words, then you can check if the string contains any word in the list.
Try the following approach
using System;
using System.Collections.Generic;
public class Program
{
private static final List<String> curseWords = new List<String>() {"123", "abc"};
public static void Main()
{
String input = "text to be checked with word abc";
if(isContainCurseWord(input)){
Console.WriteLine("Input Contains atlease one curse word");
}else{
Console.WriteLine("input does not contain any curse words")
}
}
public static bool isContainCurseWord(String text){
for(String curse in curseWords){
if(text.Contains(curse)){
return true;
}
}
return false;
}
}
Try -
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var input = "some random string with abc and 123";
var words = new List<String>() {"123", "abc"};
var foundAll = words.Any(word => input.Contains(word));
Console.WriteLine("Contains: {0}", foundAll);
}
}
Try -
var array = new List<String>() {"123", "abc"};
var found = array.Contains("abc");
Console.WriteLine("Contains: {0}", found);
i need to split a string in C# .net.
output i am getting : i:0#.f|membership|sdp950452#abctechnologies.com or i:0#.f|membership|tss954652#abctechnologies.com
I need to remove i:0#.f|membership| and #abctechnologies.com from the string. out put i need is sdp950452 or tss954652
also one more string I am getting is Pawar, Jaywardhan and i need it to be jaywardhan pawar
thanks,
Jay
Here is code example how you can do first part with Regex and the second with Splits and Replaces:
using System;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
public class Program
{
public static void Main()
{
//First part
string first = "i:0#.f|membership|sdp950452#abctechnologies.com";
string second = "i:0#.f|membership|tss954652#abctechnologies.com";
string pattern = #"\|[A-Za-z0-9]+\#";
Regex reg = new Regex(pattern);
Match m1 = reg.Match(first);
Match m2 = reg.Match(second);
string result1 = m1.Value.Replace("|",string.Empty).Replace("#",string.Empty);
string result2 = m2.Value.Replace("|", string.Empty).Replace("#", string.Empty);
Console.WriteLine(result1);
Console.WriteLine(result2);
//Second part
string inputString = "Pawar, Jaywardhan";
string a = inputString.ToLower();
var b = a.Split(' ');
var result3 = b[1] + " " + b[0].Replace(",",string.Empty);
}
}
}
Using Linq to reduce the code lines
Link to dotnetfiddle code sample
using System.Linq;
using System;
public class Program
{
public static void Main()
{
//Extract email
string a = "i:0#.f|membership|sdp950452#abctechnologies.com";
string s = a.Split('|').Where(splitted => splitted.Contains("#")).FirstOrDefault().Split('#').First();
Console.WriteLine(s);
//Format Name
string name = "Pawar, Jaywardhan";
string formatted = String.Join(" ",name.Split(',').Reverse()).ToLower().TrimStart().TrimEnd();
Console.WriteLine(formatted);
}
}
I have a string
"[\"1,1\",\"2,2\"]"
and I want to turn this string onto this
1,1,2,2
I am using Replace function for that like
obj.str.Replace("[","").Replace("]","").Replace("\\","");
But it does not return the expected result.
Please help.
You haven't removed the double quotes. Use the following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\\","").Replace("\"", "");
Here is an optimized approach in case the string or the list of exclude-characters is long:
public static class StringExtensions
{
public static String RemoveAll(this string input, params Char[] charactersToRemove)
{
if(string.IsNullOrEmpty(input) || (charactersToRemove==null || charactersToRemove.Length==0))
return input;
var exclude = new HashSet<Char>(charactersToRemove); // removes duplicates and has constant lookup time
var sb = new StringBuilder(input.Length);
foreach (Char c in input)
{
if (!exclude.Contains(c))
sb.Append(c);
}
return sb.ToString();
}
}
Use it in this way:
str = str.RemoveAll('"', '[', ']', '\\');
// or use a string as "remove-array":
string removeChars = "\"{[]\\";
str = str.RemoveAll(removeChars.ToCharArray());
You should do following:
obj.str = obj.str.Replace("[","").Replace("]","").Replace("\"","");
string.Replace method does not replace string content in place. This means that if you have
string test = "12345" and do
test.Replace("2", "1");
test string will still be "12345". Replace doesn't change string itself, but creates new string with replaced content. So you need to assign this new string to a new or same variable
changedTest = test.Replace("2", "1");
Now, changedTest will containt "11345".
Another note on your code is that you don't actually have \ character in your string. It's only displayed in order to escape quote character. If you want to know more about this, please read MSDN article on string literals.
how about
var exclusions = new HashSet<char>(new[] { '"', '[', ']', '\\' });
return new string(obj.str.Where(c => !exclusions.Contains(c)).ToArray());
To do it all in one sweep.
As Tim Schmelter writes, if you wanted to do it often, especially with large exclusion sets over long strings, you could make an extension like this.
public static string Strip(
this string source,
params char[] exclusions)
{
if (!exclusions.Any())
{
return source;
}
var mask = new HashSet<char>(exclusions);
var result = new StringBuilder(source.Length);
foreach (var c in source.Where(c => !mask.Contains(c)))
{
result.Append(c);
}
return result.ToString();
}
so you could do,
var result = "[\"1,1\",\"2,2\"]".Strip('"', '[', ']', '\\');
Capture the numbers only with this regular expression [0-9]+ and then concatenate the matches:
var input = "[\"1,1\",\"2,2\"]";
var regex = new Regex("[0-9]+");
var matches = regex.Matches(input).Cast<Match>().Select(m => m.Value);
var result = string.Join(",", matches);
I have different string that starts and ends with { } like so {somestring}. I want to remove the delimiters from the string so that it shows somestring only. I can't do anything that counts the letters because I don't always know the length of the string.
Maybe this will help. Here is the code, somewhere here I want to delete the delimiters.
private static MvcHtmlString RenderDropDownList(FieldModel model)
{
ISerializer serializer = new SerializeJSon();
var value = "";
var tb1 = new TagBuilder("select");
tb1.MergeAttribute("id", model.QuestionId);
tb1.MergeAttribute("name", model.QuestionId);
tb1.MergeAttributes(GetHtmlAttributes(model.HtmlAttributes));
tb1.AddCssClass("form-field");
var sb = new StringBuilder();
MatchCollection matches = RegexHelper.GetBetweenDelimiter(model.FieldValues, "{", "}");
foreach (Match match in matches)
{
var o = match; //Solution var o = match.toString();
var tb2 = new TagBuilder("option");
//Solution string newString = o.trim(new [] { "{","}"});
tb2.SetInnerText(o.ToString()); //Solution tb2.SetInnerText(newString);
sb.Append(tb2.ToString(TagRenderMode.Normal) + "\n");
}
tb1.InnerHtml = sb.ToString();
return new MvcHtmlString(tb1.ToString(TagRenderMode.Normal));
}
string newString = originalString.Trim(new[] {'{', '}'});
Can you use Replace
string somestring = somestring.Replace("{","").Replace("}","");
Alternatively, you can use StartsWith and EndsWith which will only remove from the beginning and the end of the string, for example:
string foo = "{something}";
if (foo.StartsWith("{"))
{
foo = foo.Remove(0, 1);
}
if (foo.EndsWith("}"))
{
foo = foo.Remove(foo.Length-1, 1);
}
You could use replace e.g.
string someString = "{somestring}";
string someOtherString = someString.Replace("{","").Replace("}","");