Split string with colon (:) and separate the numbers with colon - c#

Hello i had a problem on separating a string.
Below are the sample string.
Input - D93:E93 E98 E9:E10 E26 D76:E76 D83:E83 D121:D124
Output - D93, E93, E98, E9, E10, E26, D76, E76, D83, E83, D121, D122, D123, D124
If you separate the two with the same letter it continues counting.
Please help me..
Regards,

You can do:
var input = "D93:E93 E98 E9:E10 E26 D76:E76 D83:E83 D121:D124";
var list = input.Split(' ');
var result = new List<String>();
foreach (var item in list)
{
var parts = item.Split(':');
if (parts.Length == 1) result.Add(parts[0]);
else
{
if (parts[0].Substring(0, 1).CompareTo(parts[1].Substring(0, 1)) == 0)
{
var i = Convert.ToInt32(parts[0].Substring(1));
var j = Convert.ToInt32(parts[1].Substring(1));
while (i < j)
{
result.Add(parts[0].Substring(0, 1) + i);
i++;
}
if (i == j)
{
result.Add(parts[0].Substring(0, 1) + i);
}
}
else
{
result.Add(parts[0]);
result.Add(parts[1]);
}
}
}
Console.WriteLine(string.Join(", ", result));
//output
D93, E93, E98, E9, E10, E26, D76, E76, D83, E83, D121, D122, D123, D124

The easiest way would be to use a combination of String.Split() and String.Join():
var result = String.Join(", ", s.Split(':', ' '));

Try string.Split
string input = "D93:E93 E98 E9:E10 E26 D76:E76 D83:E83 D121:D124";
var output = input.Split(new [] {':', ' '});
Console.WriteLine(output);
or if you need the commas:
string input = "D93:E93 E98 E9:E10 E26 D76:E76 D83:E83 D121:D124";
var output = input.Split(new [] {':', ' '});
var outstr = output.Aggregate((a,e) => a + ", " + e);
Console.WriteLine(outstr);

Related

problems with for loop string

I'm new to programming in c# and I'm trying to figure out how I could
potentially reverse all words except words containing e in a string.
my current code will detect words containing e, and just writes them down in another textbox:
string text = txbInput.Text;
var words = text.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Contains('e'))
{
txbOutput.Text += words[i];
}
Current:
Input: chicken crossing the road
Output: chickenthe
.
Expected outcome:
Input: chicken crossing the road
Output chicken gnissorc the daor
You can simply split the word on the space character, then, for each word, select either the word itself, or the word reversed (depending on whether or not it contains the 'e' character), and then join them back together again with the space character:
txbOutput.Text = string.Join(" ", txbInput.Text.Split(' ')
.Select(word => word.Contains("e") ? string.Concat(word.Reverse()) : word));
Outputs: chicken gnissorc the daor
using System;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
var input = "chicken crossing the road";
foreach (var item in input.Split(' '))
{
if (item.Contains('e'))
{
Console.Write(item + ' ');
}
else
{
Console.Write(Reverse(item) + ' ');
}
}
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
}
enter code here
EDIT
foreach (var item in input.Split(' '))
{
if (item.Contains('e'))
{
txbOutput.Text = txbOutput.Text+ item + ' ';
}
else
{
txbOutput.Text= txbOutput.Text+ Reverse(item) + ' ';
}
}
You can try using the following code -
string.Join(” “,
str.Split(‘ ‘)
.Select(x => new String(x.Reverse().ToArray()))
.ToArray());
Copied from - https://www.declarecode.com/code-solutions/csharp/caprogramtoreverseeachwordinthegivenstring

Is there a simple way to apply grammatical casing to a string?

I am developing a Xamarin.Forms application on UWP
I have an Editor control - Basically a multi-line TextBox
I am trying to apply some simple grammatical casing to the string basically the following:
Capitalise the word "I"
Capitalise the First word
Capitalise the First word after a full stop.
I have managed to do the first two, and am a bit stuck on the third and was wondering if there is an easier way or whether my algorithm can be adapted.
What I have so far is:
public static string ToGramaticalCase(this string s)
{
var thingsToCapitalise = new String[] {"i"};
string newString = string.Empty;
if (!string.IsNullOrEmpty(s))
{
var wordSplit = s.Split(' ');
if (wordSplit.Count() > 1)
{
var wordToCapitalise = wordSplit.First();
wordToCapitalise = wordToCapitalise.Substring(0, 1).ToUpper() + wordToCapitalise.Substring(1);
var value = wordToCapitalise + s.Substring(wordToCapitalise.Length);
foreach (var item in thingsToCapitalise)
{
value = value.Replace(string.Format(" {0} ", item), string.Format(" {0} ", item.ToUpper()));
}
newString = value;
}
}
return newString;
}
This method will capitalize all words after ". ":
[Test]
public void Test()
{
var result = NewSentenceWithUpperLetter("Sentence one. sentence two.");
// result will be 'Sentence one. Sentence two.'
}
private string NewSentenceWithUpperLetter(string text)
{
var splitted = text.Split(' ');
for (var i = 1; i < splitted.Length; i++)
{
if (splitted[i - 1].EndsWith("."))
{
splitted[i] = splitted[i][0].ToString().ToUpper() + splitted[i].Substring(1);
}
}
return string.Join(" ", splitted);
}
Just split the string also on full stop. Change this line:
var wordSplit = s.Split(' ');
Into this:
var wordSplit = s.Split(new char[] { ' ', '.' },StringSplitOptions.RemoveEmptyEntries);
Edit
This extension method would do what you want:
public static string ToTitleCase(this string input)
{
string output =
String.Join(" ", input.Split(new char[] { ' ' },StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Select(x => x = x.Length>1?
x.First().ToString().ToUpper() + x.Substring(1):
x.First().ToString().ToUpper()));
output =
String.Join(".", output.Split(new char[] { '.' },StringSplitOptions.RemoveEmptyEntries)
.ToList()
.Select(x => x = x.Length > 1 ?
x.First().ToString().ToUpper() + x.Substring(1) :
x.First().ToString().ToUpper()));
return output;
}
Test string: string input = "i try this test sentence .now it works as i want";
Output: I Try This Test Sentence .Now It Works As I Want

Split string and keeping the delimiter without Regex C#

Problem: spending too much time solving simple problems. Oh, here's the simple problem.
Input: string inStr, char delimiter
Output: string[] outStrs where string.Join("", outStrs) == inStr and each item in outStrs before the last item must end with the delimiter. If inStr ends with the delimiter, then the last item in outStrs ends with the delimiter as well.
Example 1:
Input: "my,string,separated,by,commas", ','
Output: ["my,", "string,", "separated,", "by,", "commas"]
Example 2:
Input: "my,string,separated,by,commas,", ','
Output: ["my,", "string,", "separated,", "by,", "commas,"] (notice trailing comma)
Solution with Regex: here
I want to avoid using Regex, simply because this requires only character comparison. It's algorithmically just as complex to do as what string.Split() does. It bothers me that I cannot find a more succinct way to do what I want.
My bad solution, which doesn't work for me... it should be faster and more succinct.
var outStr = inStr.Split(new[]{delimiter},
StringSplitOptions.RemoveEmptyEntries)
.Select(x => x + delimiter).ToArray();
if (inStr.Last() != delimiter) {
var lastOutStr = outStr.Last();
outStr[outStr.Length-1] = lastOutStr.Substring(0, lastOutStr.Length-1);
}
Using LINQ:
string input = "my,string,separated,by,commas";
string[] groups = input.Split(',');
string[] output = groups
.Select((x, idx) => x + (idx < groups.Length - 1 ? "," : string.Empty))
.Where(x => x != "")
.ToArray();
Split the string into groups, then transform every group that is not the last element by appending a comma to it.
Just thought of another way you could do it, but I don't think this method is as clear:
string[] output = (input + ',').Split( new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x + ',').ToArray();
Seems pretty simple to me without using Regex:
string inStr = "dasdasdas";
char delimiter = 'A';
string[] result = inStr.Split(new string[] { inStr }, System.StringSplitOptions.RemoveEmptyEntries);
string lastItem = result[result.Length - 1];
int amountOfLoops = lastItem[lastItem.Length - 1] == delimiter ? result.Length - 1 : result.Length - 2;
for (int i = 0; i < amountOfLoops; i++)
{
result[i] += delimiter;
}
public static IEnumerable<string> SplitAndKeep(this string s, string[] delims)
{
int start = 0, index;
string selectedSeperator = null;
while ((index = s.IndexOfAny(delims, start, out selectedSeperator)) != -1)
{
if (selectedSeperator == null)
continue;
if (index - start > 0)
yield return s.Substring(start, index - start);
yield return s.Substring(index, selectedSeperator.Length);
start = index + selectedSeperator.Length;
}
if (start < s.Length)
{
yield return s.Substring(start);
}
}

How do i replace first letter in each word in a string?

string str = "ghy saste mater"
How do I replace first letter in each word from str to the letter "w"?
So the new string would be:
"why waste water"
How can I achieve this?
You would explode string.Split() your string using the delimeter of " " this would give you an array of strings and then you can loop over the entire array and call:
string.Replace(string[0], 'w')
A far more impressive manner of doing this would be using Regex.Replace() and writing a Regex to find the combination of a space and a character and then replace that string with a space and a w.
something like " a" would be replaced with " w"
This is really straitforward so I only provided some hints. Look-up what I talked about here and you'll be fine.
Try this :
string str = "ghy saste mater";
string[] parts = str.Split(' ');
string result = string.Join(" ", parts.Select(p => "w" + (p.Length > 1 ? p.Substring(1, p.Length - 1) : "")).ToArray());
You could split the string into an array and then change the first character in each element of the new array.
Something like:
string[] str_array = str.Split(' ');
for (int i = 0; i < str_array.Length; i++) {
str_array[i] = "w" + str_array[i].Substring(1, str_array[i].Length);
}
Then you would have to turn the array back into a string.
A neat way is to use Regex.Replace():
string str = "ghy saste mater";
var strModified = Regex.Replace(str, #"\b\w", "w");
You also could use LINQ:
var str = "ghy saste mater"
var strModified = string.Join(" ", str.Split().Select(s => "w" + s.Substring(1, s.Length - 1))));
If you modify strings a lot, consider using StringBuilder class:
var str = "ghy saste mater"
var strModified = str.Split().Select(s => "w" + s.Substring(1, s.Length - 1)).
Aggregate(new StringBuilder(), (b, s) => b.Append(s + " ")).ToString();
Just iterate through it.
string o = "";
o += str[0]
for (int i = 1; i < str.length; i++){
o+=str[i-1] == ' ' ? 'w' : str[i];
}

How do I break a long String in c# without breaking a words

I want to break a long String in c# without breaking a words
Example: S AAA BBBBBBB CC DDDDDD V Breaking Character on 7 Count:
S AAA
BBBBBBB
CC
DDDDDD
V
How do I do this?
string inputStr = "S AAA BBBBBBB CC DDDDDD V ";
int maxWordLength = 7;
char separator = ' ';
string[] splitted = inputStr.Split(new[]{separator}, StringSplitOptions.RemoveEmptyEntries);
var joined = new Stack<string>();
joined.Push(splitted[0]);
foreach (var str in splitted.Skip(1))
{
var strFromStack = joined.Pop();
var joindedStr = strFromStack + separator + str;
if(joindedStr.Length > maxWordLength)
{
joined.Push(strFromStack);
joined.Push(str);
}
else
{
joined.Push(joindedStr);
}
}
var result = joined.Reverse().ToArray();
Console.WriteLine ("number of words: {0}", result.Length);
Console.WriteLine( string.Join(Environment.NewLine, result) );
prints:
number of words: 5
S AAA
BBBBBBB
CC
DDDDDD
V
Here's a shorter solution harnessing the power of regular expressions.
string input = "S AAA BBBBBBB CC DDDDDD V";
// Match up to 7 characters with optional trailing whitespace, but only on word boundaries
string pattern = #"\b.{1,7}\s*\b";
var matches = Regex.Matches(input, pattern);
foreach (var match in matches)
{
Debug.WriteLine(match.ToString());
}
This does the trick if I've understood your question correctly. A recursive implementation would have been cooler, but tail recursion is too damn bad in C# :)
Could also be implemented with yield and IEnumerable<string>.
string[] splitSpecial(string words, int lenght)
{
// The new result, will be turned into string[]
var newSplit = new List<string>();
// Split on normal chars, ie newline, space etc
var splitted = words.Split();
// Start out with null
string word = null;
for (int i = 0; i < splitted.Length; i++)
{
// If first word, add
if (word == null)
{
word = splitted[i];
}
// If too long, add
else if (splitted[i].Length + 1 + word.Length > lenght)
{
newSplit.Add(word);
word = splitted[i];
}
// Else, concatenate and go again
else
{
word += " " + splitted[i];
}
}
// Flush what we have left, ie the last word
newSplit.Add(word);
// Convert into string[] (a requirement?)
return newSplit.ToArray();
}
Why not to try regex?
(?:^|\s)(?:(.{1,7}|\S{7,}))(?=\s|$)
and use all captures.
C# code:
var text = "S AAA BBBBBBB CC DDDDDD V";
var matches = new Regex(#"(?:^|\s)(?:(.{1,7}|\S{7,}))(?=\s|$)").Matches(text).Cast<Match>().Select(x => x.Groups[1].Value).ToArray();
foreach (var match in matches)
{
Console.WriteLine(match);
}
Output:
S AAA
BBBBBBB
CC
DDDDDD
V
string str = "S AAA BBBBBBB CC DDDDDD V";
var words = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb = new StringBuilder();
List<string> result = new List<string>();
for (int i = 0; i < words.Length; ++i)
{
if (sb.Length == 0)
{
sb.Append(words[i]);
}
else if (sb.Length + words[i].Length < 7)
{
sb.Append(' ');
sb.Append(words[i]);
}
else
{
result.Add(sb.ToString());
sb.Clear();
sb.Append(words[i]);
}
}
if (sb.Length > 0)
{
result.Add(sb.ToString());
}
Results will contain:
S AAA
BBBBBBB
CC
DDDDDD
V
The predicate can be adjusted depending on if the separator between words should be included in the 7 characters or not.
This is how to add row break to HTML text:
SplitLongText(string _SourceText, int _MaxRowLength)
{
if (_SourceText.Length < _MaxRowLength)
{
return _SourceText;
}
else
{
string _RowBreakText="";
int _CurrentPlace = 0;
while (_CurrentPlace < _SourceText.Length)
{
if (_SourceText.Length - _CurrentPlace < _MaxRowLength)
{
_RowBreakText += _SourceText.Substring(_CurrentPlace);
_CurrentPlace = _SourceText.Length;
}
else
{
string _PartString = _SourceText.Substring(_CurrentPlace, _MaxRowLength);
int _LastSpace = _PartString.LastIndexOf(" ");
if (_LastSpace > 0)
{
_RowBreakText += _PartString.Substring(0, _LastSpace) + "<br/>" + _PartString.Substring(_LastSpace, (_PartString.Length - _LastSpace));
}
else
{
_RowBreakText += _PartString + "<br/>";
}
_CurrentPlace += _MaxRowLength;
}
}
return _RowBreakText;
}
2021
Look at this extension method, it uses recursivity
public static string SubstringDontBreakWords(this string str, int maxLength)
{
return str.Length <= maxLength ? str : str.Substring(0, str.LastIndexOf(" ")).Trim().SubstringDontBreakWords(maxLength);
}
Use it like this
string text = "Hello friends";
text.SubstringDontBreakWords(10)

Categories

Resources