reverse words BUT dot should be at the end - c#

I have sentence:
"I love Marry."
and I would like to get:
"Marry love I." (dot at the end)
How can I do that?
public static string ReverseWords(string originalString)
{
return string.Join(" ", originalString.Split(' ').Where(x => !string.IsNullOrEmpty(x)).Reverse());
}

You can remove the last '.' before the split.
Demo:
public static string ReverseWords(string originalString)
{
var input = originalString.EndsWith(".") ? originalString.Remove(originalString.Length - 1) : originalString; // will trim ending '.'
return string.Join(" ", input.Split().Reverse()) + ".";
}
Try it online!

Try this. I am making it into several statements for readability.
var words = originalString.Split(new [] {' ', '.'}, StringSplitOptions.RemoveEmptyEntries).Reverse();
That gets your words in reverse order, and avoids the need for your Where clause. Then join them back with the period:
return string.Join(' ', words) + '.';

Do it in two steps where you split on . first;
return
string.Join(".",
originalString.Split('.')
.ToList()
.Select(s => string.Join(" ", s.Split(' ').Where(x => !string.IsNullOrEmpty(x)).Reverse())));

For single sentences, remove the dot and append it again in the end.
To remove the dot you can use TrimEnd which will remove all dots from the end of the string. If there is none, nothing is removed:
public static string ReverseWords(string originalString)
{
originalString = originalString.TrimEnd('.');
originalString = string.Join(" ", originalString.Split(' ').Where(x => !string.IsNullOrEmpty(x)).Reverse());
return originalString + ".";
}
For multiple senctences you can split the input string at the ., which will give you an array of sentences without dots. Then you simply reverse each part, append a dot and put them back together (I used a StringBuilder to do that):
public static string ReverseWordsMultiple(string originalString)
{
String[] sentences = originalString.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
StringBuilder builder = new StringBuilder();
foreach (String senctence in sentences)
{
builder.Append(string.Join(" ", senctence.Split(' ').Where(x => !string.IsNullOrEmpty(x)).Reverse()));
builder.Append(". ");
}
return builder.ToString().TrimEnd();
}

Related

Split word from string

I use this method for splitting words from string, but \n doesn't consider. How can I solve it?
public string SplitXWord(string text, int wordCount)
{
string output = "";
IEnumerable<string> words = text.Split().Take(wordCount);
foreach (string word in words)
{
output += " " + word;
}
return output;
}
Well, string.Split() splits by white-spaces only
https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=net-6.0
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
bold is mine.
So far so good, string.Split() splits on spaces ' ', tabulation '\t', new line '\n', carriage return '\r' etc.:
Console.Write(string.Join(", ", "a\nb\rc\td e".Split()));
produces
a, b, c, d, e
If you want to split on your cown delimiters, you should prvide them:
Console.Write(string.Join(", ", "a\nb\rc\td e".Split(new char[] {' ', '\t'})));
note that \r and \n are preserved, when splitted on ' ' and 't'
a
b
c, d, e
So, it seems that your method should be something like this:
using System.Linq;
...
//DONE: static - we don't want this here
public static string SplitXWord(string text, int wordCount) {
//DONE: don't forget about degenerated cases
if (string.IsNullOrWhiteSpace(text) || wordCount <= 0)
return "";
//TODO: specify delimiters on which you want to split
return string.Join(" ", text
.Split(
new char[] { ' ', '\t' },
wordCount + 1,
StringSplitOptions.RemoveEmptyEntries)
.Take(wordCount));
}
Use the overload of Split method which accepts an array of char separators and clears the empty entries
string str = "my test \n\r string \n is here";
string[] words = str.Split(new []{' ', '\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
UPDATE:
Another solution with regex and keeping line characters:
string str = "my test\r\n string\n is here";
var wordsByRegex = Regex.Split(str, #"(?= ).+?(\r|\n|\r\n)?").ToList();
fiddle
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp17
{
class Program
{
static void Main(string[] args)
{
string myStr = "hello my friend \n whats up \n bro";
string[] mySplitStr = myStr.Split("\n");
mySplitStr.ToList().ForEach(str=>{
Console.WriteLine(str);
//to remove the white spaces
//Console.WriteLine(str.Replace(" ",""));
});
Console.ReadLine();
}
}
}

C# - Identify the matching character when using String.Split(CharArray)

If I use the Split() function on a string, passing in various split characters as a char[] parameter, and given that the matching split character is removed from the string, how can I identify which character it matched & split on?
string inputString = "Hello, there| world";
char[] splitChars = new char[] { ',','|' }
foreach(string section in inputString.Split(splitChars))
{
Console.WriteLine(section) // [0] Hello [1} there [2] world (no splitChars)
}
I understand that perhaps its not possible to retain this information with my approach. If thats the case, could you suggest an alternative approach?
The C# Regex.Split() method documented here can return the split characters as well as the words between them.
string inputString = "Hello, there| world";
string pattern = #"(,)|([|])";
foreach (string result in Regex.Split(inputString, pattern))
{
Console.WriteLine("'{0}'", result);
}
the result is:
'Hello'
','
' there'
'|'
' world'
Use the Regex.Split() method. I have wrapped this method in the following extension method that is as easy to use as string.Split() itself:
public static string[] ExtendedSplit(this string input, char[] splitChars)
{
string pattern = string.Join("|", splitChars.Select(x => "(" + Regex.Escape(x.ToString()) + ")"));
return Regex.Split(input, pattern);
}
Usage:
string inputString = "Hello, there| world";
char[] splitChars = new char[]{',', '|'};
foreach (string result in inputString.ExtendedSplit(splitChars))
{
Console.WriteLine("'{0}'", result);
}
Output:
'Hello'
','
' there'
'|'
' world'
No, but its rather trivial to write one yourself. Remember, framework methods aren't magic, somebody wrote them. If something doesn't exactly match your needs, write one that does!
static IEnumerable<(string Sector, char Separator)> Split(
this string s,
IEnumerable<char> separators,
bool removeEmptyEntries)
{
var buffer = new StringBuilder();
var separatorsSet = new HashSet<char>(separators);
foreach (var c in s)
{
if (separatorsSet.Contains(c))
{
if (!removeEmptyEntries || buffer.Length > 0)
yield return (buffer.ToString(), c);
buffer.Clear();
}
else
buffer.Append(c);
}
if (buffer.Length > 0)
yield return (buffer.ToString(), default(char));
}

c# split string and remove empty string

I want to remove empty and null string in the split operation:
string number = "9811456789, ";
List<string> mobileNos = number.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(mobile => mobile.Trim()).ToList();
I tried this but this is not removing the empty space entry
var mobileNos = number.Replace(" ", "")
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
As I understand it can help to you;
string number = "9811456789, ";
List<string> mobileNos = number.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
the result only one element in list as [0] = "9811456789".
Hope it helps to you.
a string extension can do this in neat way as below
the extension :
public static IEnumerable<string> SplitAndTrim(this string value, params char[] separators)
{
Ensure.Argument.NotNull(value, "source");
return value.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
}
then you can use it with any string as below
char[] separator = { ' ', '-' };
var mobileNos = number.SplitAndTrim(separator);
I know it's an old question, but the following works just fine:
string number = "9811456789, ";
List<string> mobileNos = number.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
No need for extension methods or whatsoever.
"string,,,,string2".Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return ["string"],["string2"]
The easiest and best solution is to use both StringSplitOptions.TrimEntries to trim the results and StringSplitOptions.RemoveEmptyEntries to remove empty entries, fed in through the pipe operator (|).
string number = "9811456789, ";
List<string> mobileNos = number
.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.ToList();
Checkout the below test results to compare how each option works,

manipulating strings

I am trying to remove some special characters from a string.
I have got the following string
[_fesd][009] Statement
and I want to get rid of all '_' '[' and ']'
I managed to remove the first characters with TrimStart and I get fesd][009] Statement
How should I remove the special characters from the middle of my string?
Currently Im using the following code
string newStr = str.Trim(new Char[] { '[', ']', '_' });
where str is the strin that should be manupulated and the result should be stored in newStr
string newStr = str.Replace("[", "").Replace("]", "").Replace("_", "");
var newStr = Regex.Replace("[_fesd][009] Statement", "(\\[)|(\\])|(_)", string.Empty);
Use string.Replace with string.Empty as the string to replace with.
You could use Linq for it:
static void Main(string[] args)
{
var s = #"[_fesd][009] Statement";
var unwanted = #"_[]";
var sanitizedS = s
.Where(i => !unwanted.Contains(i))
.Aggregate<char, string>("", (a, b) => a + b);
Console.WriteLine(sanitizedS);
// output: fesd009 Statement
}
var chars = new Char[] { '[', ']', '_' };
var newValue = new String(str.Where(x => !chars.Contains(x)).ToArray());

How do I split a string by a multi-character delimiter in C#?

What if I want to split a string using a delimiter that is a word?
For example, This is a sentence.
I want to split on is and get This and a sentence.
In Java, I can send in a string as a delimiter, but how do I accomplish this in C#?
http://msdn.microsoft.com/en-us/library/system.string.split.aspx
Example from the docs:
string source = "[stop]ONE[stop][stop]TWO[stop][stop][stop]THREE[stop][stop]";
string[] stringSeparators = new string[] {"[stop]"};
string[] result;
// ...
result = source.Split(stringSeparators, StringSplitOptions.None);
foreach (string s in result)
{
Console.Write("'{0}' ", String.IsNullOrEmpty(s) ? "<>" : s);
}
You can use the Regex.Split method, something like this:
Regex regex = new Regex(#"\bis\b");
string[] substrings = regex.Split("This is a sentence");
foreach (string match in substrings)
{
Console.WriteLine("'{0}'", match);
}
Edit: This satisfies the example you gave. Note that an ordinary String.Split will also split on the "is" at the end of the word "This", hence why I used the Regex method and included the word boundaries around the "is". Note, however, that if you just wrote this example in error, then String.Split will probably suffice.
Based on existing responses on this post, this simplify the implementation :)
namespace System
{
public static class BaseTypesExtensions
{
/// <summary>
/// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
/// </summary>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns></returns>
public static string[] Split(this string s, string separator)
{
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
}
}
string s = "This is a sentence.";
string[] res = s.Split(new string[]{ " is " }, StringSplitOptions.None);
for(int i=0; i<res.length; i++)
Console.Write(res[i]);
EDIT: The "is" is padded on both sides with spaces in the array in order to preserve the fact that you only want the word "is" removed from the sentence and the word "this" to remain intact.
...In short:
string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);
Or use this code; ( same : new String[] )
.Split(new[] { "Test Test" }, StringSplitOptions.None)
You can use String.Replace() to replace your desired split string with a character that does not occur in the string and then use String.Split on that character to split the resultant string for the same effect.
Here is an extension function to do the split with a string separator:
public static string[] Split(this string value, string seperator)
{
return value.Split(new string[] { seperator }, StringSplitOptions.None);
}
Example of usage:
string mystring = "one[split on me]two[split on me]three[split on me]four";
var splitStrings = mystring.Split("[split on me]");
var dict = File.ReadLines("test.txt")
.Where(line => !string.IsNullOrWhitespace(line))
.Select(line => line.Split(new char[] { '=' }, 2, 0))
.ToDictionary(parts => parts[0], parts => parts[1]);
or
enter code here
line="to=xxx#gmail.com=yyy#yahoo.co.in";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);
ans:
tokens[0]=to
token[1]=xxx#gmail.com=yyy#yahoo.co.in
string strData = "This is much easier"
int intDelimiterIndx = strData.IndexOf("is");
int intDelimiterLength = "is".Length;
str1 = strData.Substring(0, intDelimiterIndx);
str2 = strData.Substring(intDelimiterIndx + intDelimiterLength, strData.Length - (intDelimiterIndx + intDelimiterLength));

Categories