How to take n part of String using Split() method in C#? - c#

I have string str = "Join Smith hate meat".
I want to get JoinSmith from this str.
I tried code:
private static string GetFirstWord(string str)
{
return str.Split(' ').Take(2).ToString();
}
This code not working for me.
I tried: return str.Split(' ').FirstOrDefault it get only first part of string Join.

Use
string result = string.Concat(str.Split(' ').Take(2)); // "JoinSmith"

A Fancy combination:
var result = string.Join(String.Empty, str.Split(' ').Take(2));
Takes the first two words, joins them into one string.
Or:
var result = string.Concat(str.Split(' ').Take(2));

Something a little different
var result = new string(TakeAllUntilSecondSpace(str).ToArray());
Yield the characters you want... sometimes this is a good way if you need a lot of control that standard methods don't provide.
private IEnumerable<char> TakeAllUntilSecondSpace(string s)
{
var spaceEncountered = false;
foreach (char c in s)
{
if (c == ' ')
{
if (spaceEncountered) yield break;
spaceEncountered = true;
} else yield return c;
}
}

Related

how do find the same string and difference string in List<string>?

I have list like this:
List<string> myList = new List<string>()
{
"AS2258B43C014AI9954803",
"AS2258B43C014AI9954603",
"AS2258B43C014AI9954703",
"AS2258B43C014AI9954503",
"AS2258B43C014AI9954403",
"AS2258B43C014AI9954203",
"AS2258B43C014AI9954303",
"AS2258B43C014AI9954103",
};
I want to output something format is sameString+diffString0\diffString1\diffString2.... like this "AS2258B43C014AI9954803\603\703\503\403\203\303\103"
what should I do?
You can create a method which returns you the difference between to strings:
private static string GetDiff (string s1, string s2)
{
int i;
for(i = 0; i < Math.Min(s1.Length,s2.Length); i++)
{
if(s1[i] != s2[i])
{
break;
}
}
return s2.Substring(i);
}
This method iterats until the first character which is different and returns the remaining characters of the second string.
With that method, you can obtain your result with the LINQ query:
string first = myList[0];
string result = first + "/" + string.Join("/", myList.Skip(1).Select(x => GetDiff(first,x)));
Online demo: https://dotnetfiddle.net/TPkhmz
Alphanumeric sorting using LINQ
Create static method for pads
public static string PadNumbers(string input)
{
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}
then call it
var result = myList.OrderBy(x => PadNumbers(x));
after that you can find the difference
The simplest solution is to create a function like this :
public static string Output(List<String> ListString)
{
string sameString = ListString.First().Substring(0, 18);
string output = sameString;
foreach (var item in ListString)
{
output += item.Substring(19);
output += "\\";
}
return output.Substring(0, output.Length - 1);
}

How to remove all but the first occurences of a character from a string?

I have a string of text and want to ensure that it contains at most one single occurrence of a specific character (,). Therefore I want to keep the first one, but simply remove all further occurrences of that character.
How could I do this the most elegant way using C#?
This works, but not the most elegant for sure :-)
string a = "12,34,56,789";
int pos = 1 + a.IndexOf(',');
return a.Substring(0, pos) + a.Substring(pos).Replace(",", string.Empty);
You could use a counter variable and a StringBuilder to create the new string efficiently:
var sb = new StringBuilder(text.Length);
int maxCount = 1;
int currentCount = 0;
char specialChar = ',';
foreach(char c in text)
if(c != specialChar || ++currentCount <= maxCount)
sb.Append(c);
text = sb.ToString();
This approach is not the shortest but it's efficient and you can specify the char-count to keep.
Here's a more "elegant" way using LINQ:
int commasFound = 0; int maxCommas = 1;
text = new string(text.Where(c => c != ',' || ++commasFound <= maxCommas).ToArray());
I don't like it because it requires to modify a variable from a query, so it's causing a side-effect.
Regular expressions are elegant, right?
Regex.Replace("Eats, shoots, and leaves.", #"(?<=,.*),", "");
This replaces every comma, as long as there is a comma before it, with nothing.
(Actually, it's probably not elegant - it may only be one line of code, but it may also be O(n^2)...)
If you don't deal with large strings and you reaaaaaaly like Linq oneliners:
public static string KeepFirstOccurence (this string #string, char #char)
{
var index = #string.IndexOf(#char);
return String.Concat(String.Concat(#string.TakeWhile(x => #string.IndexOf(x) < index + 1)), String.Concat(#string.SkipWhile(x=>#string.IndexOf(x) < index)).Replace(#char.ToString(), ""));
}
You could write a function like the following one that would split the string into two sections based on the location of what you were searching (via the String.Split() method) for and it would only remove matches from the second section (using String.Replace()) :
public static string RemoveAllButFirst(string s, string stuffToRemove)
{
// Check if the stuff to replace exists and if not, return the original string
var locationOfStuff = s.IndexOf(stuffToRemove);
if (locationOfStuff < 0)
{
return s;
}
// Calculate where to pull the first string from and then replace the rest of the string
var splitLocation = locationOfStuff + stuffToRemove.Length;
return s.Substring(0, splitLocation) + (s.Substring(splitLocation)).Replace(stuffToRemove,"");
}
You could simply call it by using :
var output = RemoveAllButFirst(input,",");
A prettier approach might actually involve building an extension method that handled this a bit more cleanly :
public static class StringExtensions
{
public static string RemoveAllButFirst(this string s, string stuffToRemove)
{
// Check if the stuff to replace exists and if not, return the
// original string
var locationOfStuff = s.IndexOf(stuffToRemove);
if (locationOfStuff < 0)
{
return s;
}
// Calculate where to pull the first string from and then replace the rest of the string
var splitLocation = locationOfStuff + stuffToRemove.Length;
return s.Substring(0, splitLocation) + (s.Substring(splitLocation)).Replace(stuffToRemove,"");
}
}
which would be called via :
var output = input.RemoveAllButFirst(",");
You can see a working example of it here.
static string KeepFirstOccurance(this string str, char c)
{
int charposition = str.IndexOf(c);
return str.Substring(0, charposition + 1) +
str.Substring(charposition, str.Length - charposition)
.Replace(c, ' ').Trim();
}
Pretty short with Linq; split string into chars, keep distinct set and join back to a string.
text = string.Join("", text.Select(c => c).Distinct());

How to Return true if String array having mix of Int and String type value converted to int in C#

I have string which I split to see if any of the split value is string. If so I want to return true else false.
string words = "1 2 c 5";
Easy approach, I can follow by converting into int array and then compare value side by side.
int[] iar = words.Split(' ').Select(s => int.TryParse(s, out n) ? n : 0).ToArray();
Can any one recommend better approach?
You can simply check without using Split:
var result = words.Any(c => !char.IsWhiteSpace(c)
&& !char.IsDigit(c));
Or using Split:
var result = words.Split()
.Any(w => w.Any(c => !char.IsDigit(c)));
The point is you can use char.IsDigit to check instead of using int.Parse or int.TryParse.
You could do this with a simple little method:
public static bool CheckForNum(string[] wordsArr)
{
int i = 0;
foreach (string s in wordsArr)
{
if (Int32.TryParse(s, out i))
{
return true;
}
}
return false;
}
Using:
bool result = CheckForNum(words.Split(' '));
Console.Write(result);
Why not use a regular expression? If a string has words and numbers in it, it must have letters and number characters. I don't entirely understand the logic in your question, so you may need to adjust the logic here.
using System;
using System.Text.RegularExpressions;
...
string words = "1 2 c 5";
Match numberMatch = Regex.Match(words, #"[0-9]", RegexOptions.IgnoreCase);
Match letterMatch = Regex.Match(words, #"[a-zA-Z]", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (numberMatch.Success && letterMatch.Success)
{
// there are letters and numbers
}

To fetch the unique characters from a string?

I want to extract unique characters from a string. For example:- 'AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ' will return 'ABCFGDJ'
I have tried below piece of code but now I want to optimize it.
Please suggest if anyone knows.
static string extract(string original)
{
List<char> characters = new List<char>();
string unique = string.Empty;
foreach (char letter in original.ToCharArray())
{
if (!characters.Contains(letter))
{
characters.Add(letter);
}
}
foreach (char letter in characters)
{
unique += letter;
}
return unique;
}
I don't know if this is faster, but surely shorter
string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
var newstr = String.Join("", s.Distinct());
Another LINQ approach, but not using string.Join:
var result = new string(original.Distinct().ToArray());
I honestly don't know which approach to string creation would be faster. It probably depends on whether string.Join ends up internally converting each element to a string before appending to a StringBuilder, or whether it has custom support for some well-known types to avoid that.
How about
var result = string.Join("", "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ".Distinct());
Make sure that you include System.Linq namespace.
Try this
string str = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
string answer = new String(str.Distinct().ToArray());
I hope this helps.
if "AAABBBAAA" should return "ABA", then the following does it. Albeit not very fast.
List<char> no_repeats = new List<char>();
no_repeats.Add(s[0]);
for (int i = 1; i < s.Length; i++)
{
if (s[i] != no_repeats.Last()) no_repeats.Add(s[i]);
}
string result = string.Join("", no_repeats);

String cleaning and formatting

I have a URL formatter in my application but the problem is that the customer wants to be able to enter special characters like:
: | / - “ ‘ & * # #
I have a string:
string myCrazyString = ":|/-\“‘&*##";
I have a function where another string is being passed:
public void CleanMyString(string myStr)
{
}
How can I compare the string being passed "myStr" to "myCrazyString" and if "myStr has any of the characters in myCrazyString to remove it?
So if I pass to my function:
"this ' is a" cra#zy: me|ssage/ an-d I& want#to clea*n it"
It should return:
"this is a crazy message and I want to clean it"
How can I do this in my CleanMyString function?
Use Regular Expression for that Like:
pattern = #"(:|\||\/|\-|\\|\“|\‘|\&|\*|\#|\#)";
System.Text.RegularExpressions.Regex.Replace(inputString, pattern, string.Empty);
split each string you want to remove by |
To remove the special characters like the | itself use \, so \| this will handle the | as normal character.
Test:
inputString = #"H\I t&he|r#e!";
//output is: HI there!
solution without regular expressions, just for availability purposes:
static string clear(string input)
{
string charsToBeCleared = ":|/-\“‘&*##";
string output = "";
foreach (char c in input)
{
if (charsToBeCleared.IndexOf(c) < 0)
{
output += c;
}
}
return output;
}
You can use Regex as others mentioned, or code like this:
char[] myCrazyChars = "\"\':|/-\\“‘&*##".ToCharArray();
string myCrazyString = "this ' is a\" cra#zy: me|ssage/ an-d I& want#to clea*n it";
string[] splittedCrazyString = myCrazyString.Split(myCrazyChars);
string notCrazyStringAtAll = string.Join("", splittedCrazyString);
Try using a Regular Expression.
Here's a fairly straight-forward way to do it. Split the string based on all of the characters in your "crazy string and then join them back together without the bad characters.
string myCrazyString = #":|/-\“‘&*##";
string str = #"this ' is a"" cra#zy: me|ssage/ an-d I& want#to clea*n it";
string[] arr = str.Split(myCrazyString.ToCharArray(), StringSplitOptions.None);
str = string.Join(string.Empty, arr);
Another possible solution:
namespace RemoveChars
{
class Program
{
static string str = #"this ' is a\“ cra#zy: me|ssage/ an-d I& want#to clea*n it";
static void Main(string[] args)
{
CleanMyString(str);
}
public static void CleanMyString(string myStr)
{
string myCrazyString = #":|/-\“‘&*##";
var result = "";
foreach (char c in myStr)
{
var t = true; // t will remain true if c is not a crazy char
foreach (char ch in myCrazyString)
if (c == ch)
{
t = false;
break;
}
if (t)
result += c;
}
}
}
}
You could try an if statement and if a character is present then mention the craziness
if (myCrazyString.Contains("#"))
{
Console.WriteLine("This string is out of controL!");
}
Regex is also a good idea(Maybe better)
Try this :
1.Define a StringBuilder
2.Iterate through the characters of the string to be cleaned.
3.Put everything required in the StringBuilder and ignore other special charactersby simply putting if conditions.
4.Rerurn StringBuilder.
Or
Try using Regular Expression.

Categories

Resources