C# - split string [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have some problems with split and check string.
I need to split string, replace halfs and check is this the same as the second string.
example: first string = tokyo second string = koyto
soo... S = a+b = b+a
S - a = b and S - b = a
a and b is part of one string (S) and may have different long in this case a = to and b = koy
first I need to check string length - is the are different - then write Error - it's easy
the I thought that I can compare strings in ASCII (case sensitivity is not important) and it' could be ok but...
I can create string tooky which have got the same size in ASCII but is not created from split and invert parts of first string...
any ideas?
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
split string ?
}
else
Console.WriteLine("This two words are different. No result found.");
Console.Read();
}

I would suggest doing the comparisons with strings. You can use the String.ToLower() method to convert them both to lowercase for comparison.
I am not exactly sure what problem you are trying to solve is, but from what I understand you are trying to check if string S can be split into two substrings that can be rearranged to make string T.
To check this you will want something similar to the following
for (int i = 0; i < S.length; i++) {
string back = S.substring(i);
string front = S.substring(0,i);
if (T.equals(back + front))
result = true;
}
Hope this helps

If you want to compare equality of two collections you should consider using LINQ:
static void Main(string[] args)
{
string S = "tokyo";
string T = "kyoto";
if (S.Length == T.Length)
{
if (S.Intersect(T).Any())
{
Console.WriteLine("The Contents are the same");
Console.Read();
}
}
else
Console.WriteLine("This two words are diferent. No result found.");
Console.Read();
}

Related

c# find keywords in a string and remove it [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have got a list with keywords. And I coded a method that if a string contains keyword from list, the method must remove keyword from string. Here is the method:
private string RemoveFromList(string sentence)
{
var lists = new List<string>{ "ask-", "que-", "(app)", "(exe)", "(foo)" };
var control = lists.Any(sentence.Contains);
string result;
if (control)
{
var index = sentence.IndexOf(lists.FirstOrDefault(sentence.Contains)
?? throw new InvalidOperationException(), StringComparison.Ordinal);
result = index != -1 ? sentence.Remove(index) : sentence;
}
else
result = sentence;
return result;
}
var str = "ask- This is a sentence.";
Message.Box(RemoveFromList(str));
// It does not give to me: This is a sentence.
This method does not work properly. It does not remove the keyword from the string.
Using string.Replace is the simplest approach:
foreach (var word in lists)
{
sentence = sentence.Replace(word,"").Trim();
}
Although that will find the word in the middle of the string too. If you wanted to remove it only at the start you could use IndexOf check it's 0 and then take the string starting from word.Length using Substring. Or use StartsWith:
foreach (var word in lists)
{
if (sentence.StartsWith(word))
{
sentence = sentence.Substring(word.Length).Trim();
// break; // if only one
}
}
There are 2 options for you.
First of all the Remove usage is incorrect. You just want to remove the keyword. If u pass 1 argument to remove it will remove from that index till end. Pass the length of keyword as second arg to Remove.
s.Remove(index, len);
If string contains it than replace the occurrence of keyword with empty string
s.Replace("keyword", "");
Another option is you could create an extension since you already know what items to remove.
using System.Text.RegularExpressions;
public static string RemoveFromList(this string sentence)
{
new List<string>{ "ask-",
"que-",
"(app)",
"(exe)",
"(foo)" }.ForEach(name =>
{
sentence = Regex.Replace(sentence.Replace(name, string.Empty), " {2,}", " ");
});
return sentence;
}
Useage
var str = "ask- This is (app) a que- sentence.".RemoveFromList();
Note
I used Regex.Replace as it's possible you may have some blank spaces floating around after you remove the bad string/s, this helps ensure that doesn't happen.

String operations . Change the order and delete dome caracters of a string [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a lot of string like this "01/08/2019" and i want to have a string like this "20190801" . I cant use the DateTime format , i must do it using string as a type . Please someone to help
You can use this
string date = "01/08/2019";
string result = string.Empty;
foreach(var item in date.Split('/'))
result = string.Concat(item, result);
what do you mean that you cannot use DateTime format?
Normally you should parse the format, keep it as DateTime in memory and use .ToString(format) for presentation purposes. Doing it all in one line would look like this:
DateTime.ParseExact("01/08/2019", "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyyMMdd")
if you surely have '/' as separator,
you can split the string with '/', by this you will get string array.
you can loop on this array in descending order and keep concatenating the element of the array to form one single output.
string dateStr = "01/01/2019";
string[] dateElements = dateStr.Split('/');
string output = string.Empty;
for(int i = dateElements.Length - 1; i >= 0; i--)
{
output += dateElements[i];
}
You can write that code like that:
var input = #"01/08/2019";
var chrs = new[] {'/'};
var result = string.Concat(input.Where(c => !chrs.Contains(c)));
This way:
class Program
{
static void Main(string[] args)
{
string str = "01/08/2019";
string normalizedStr = Normalize(str);
}
private static string Normalize(string str)
{
return string.Join("-", str.Split(new char[] { '/' }).Reverse());
}
}
Basically it split the original string in many strings by char '/'
Then it reverse the order of these strings
Then it concatenate by using "-" as separator

Extract substring from the first letter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need to extract substring from string but starting with the first letter
example :
string s1 = "12 x 13 ABC 12# 15.8" substring = ABC 12# 15.8
string s2 = "25 x 32 FER #23.8" substring = FER #23.8
I tried the index of for the letter A or F but it didn't work
thanks
This should work (in case you use a non-letter character instead of x)
string SubstringThis(string input)
{
return new string(input.SkipWhile(c => !char.IsLetter(c)).ToArray());
}
Simple utility function:
string SubstringFromFirstLetter(string s)
{
for (int i=0; i < s.Length; ++i)
{
if (char.IsLetter(s[i]))
{
return s.Substring(i);
}
}
return "";
}
Keep in mind that x is a letter. Do you want it to match only capitalized letters?
public static string GetSubstringStartingWithFirstAlphaCharacter(this string toEvaluate)
{
const string pattern = "([a-zA-Z])(.+)";
var regex = new Regex(pattern);
return regex.Match(toEvaluate).Value;
}

C# read only part of whole string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a string which has a following format:
"####/xxxxx"
The text before the "/" is always an integer and I need to read it. How do I get only the integer part of this string (before the "/")?
Thank you for your help.
You can split the string on / and then use int.TryParse on the first element of array to see if it is an integer like:
string str = "1234/xxxxx";
string[] array = str.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
int number = 0;
if (str.Length == 2 && int.TryParse(array[0], out number))
{
//parsing successful.
}
else
{
//invalid number / string
}
Console.WriteLine(number);
Use IndexOf and Substring:
int indexOfSlash = text.IndexOf('/');
string beforeSlash = null;
int numBeforeSlash = int.MinValue;
if(indexOfSlash >= 0)
{
beforeSlash = text.Substring(0, indexOfSlash);
if(int.TryParse(beforeSlash, out numBeforeSlash))
{
// numBeforeSlash contains the real number
}
}
Another alternative: use a regular expression:
var re = new System.Text.RegularExpression(#"^(\d+)/", RegexOptions.Compiled);
// ideally make re a static member so it only has to be compiled once
var m = re.Match(text);
if (m.IsMatch) {
var beforeSlash = Integer.Parse(re.Groups[0].Value);
}

Looking for best way to search and replace strings in another strings [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a class that filters a lot of values. What's the best way to search/remove/replace a string in another string?
For example:
name +value (email)
The email, how to get it using? Linq? or .Split()? or Regular Expressions?
Which would have best performance?
Currently I'm using this:
string[] parts = val.Split('(');
string Email = parts[1].Replace(")", String.Empty);
On my machine, a variation of your code is the fastest (yours comes in second).
NOTE THE UNITS!! Ticks are 100 nanosecond increments.
SplitReplace takes 0.961795 ticks per call
Split takes 0.747009 ticks per call
Regex takes 2.512739 ticks per call
WithLinq takes 2.59299 ticks per call
My variation is just to only split (no replace):
string[] parts = val.Split('(', ')');
return parts[1];
The testing code...
[Test]
public void SO()
{
const string input = "name +value (email)";
TestGivenMethod(input, SplitReplace, "SplitReplace");
TestGivenMethod(input, JustSplit, "Split");
TestGivenMethod(input, WithRegex, "Regex");
TestGivenMethod(input, WithLinq, "WithLinq");
}
private void TestGivenMethod(string input, Func<string, string> method, string name)
{
Assert.AreEqual("email", method(input));
var sw = Stopwatch.StartNew();
string res = "";
for (int i = 0; i < 1000000; i++)
{
var email = method(input);
res = email;
}
sw.Stop();
Assert.AreEqual("email", res);
Console.WriteLine("{1} takes {0} ticks per call", sw.ElapsedTicks/1000000.0, name);
}
string SplitReplace(string val)
{
string[] parts = val.Split('(');
return parts[1].Replace(")", String.Empty);
}
string JustSplit(string val)
{
string[] parts = val.Split('(', ')');
return parts[1];
}
private static Regex method3Regex = new Regex(#"\(([\w#]+)\)");
string WithRegex(string val)
{
return method3Regex.Match(val).Groups[1].Value;
}
string WithLinq(string val)
{
return new string(val.SkipWhile(c => c != '(').Skip(1).TakeWhile(c => c != ')').ToArray());
}
I would recommend regular expression as I think it is invented for this reason which is search in a string and string replacement.
If I understand your question correctly, you're trying to replace the literal of (email) with an email likely provided from another source
var text = "name +value (email)";
var emailAddress = "someone#test.com";
text = Regex.Replace(text, #"\(email\)", emailAddress);
The code block above will replace '(email)' with the contents of the emailAddress variable
Be sure to add the appropriate using statement to the top of your code-file
using System.Text.RegularExpressions;
String.Split would be the most simplest and easy to understand approach as compared to Regular Expression and I am not sure How you can fit LINQ here.
As far as performance is concerned it would be best if you can do profiling against your test data to see actual performance difference between Regular Expression and String.Split

Categories