Split and add specific charcters to a string in C# - c#

I am working with key-wording modules where each word end with , and remove spaces from the string example is given below:
if string is
one man sitting with girl , baby girl , Smiling girl
then result should be
,one man sitting with girl,baby girl,Smiling girl,
I am trying this
string[] strArray = str15.Split(new char[] { ',', ';' });
if (strArray.Length >= 1)
{
foreach (string str3 in strArray)
{
if (str3 != string.Empty)
{
strr1 = strr1 + str3 + ",";
}
}
}
But not able to remove spaces from string.

The first thing you want to do is tokenise the string, using Split().
string input = "some words , not split , in a sensible , way";
string[] sections = input.Split(',');
This gives you an array of strings split by the comma delimiter, which would look something like this:
"some words "
" not split "
" in a sensible "
" way"
Now you want to trim those spaces off. The string class has a great little function called Trim() which removes all whitespace characters (spaces, tabs, etc) from the start and end of strings.
for (int i = 0; i < sections.Length; i++)
sections[i] = sections[i].Trim();
Now you have an array with strings like this:
"some words"
"not split"
"in a sensible"
"way"
Next, you want to join them back together with a comma delimiter.
string result = string.Join(",", sections);
This gives you something along the lines of this:
"some words,not split,in a sensible,way"
And finally, you can add the commas at the start and end:
result = "," + result + ",";
Of course, this isn't the cleanest way of doing it. It's just an easy way of describing the individual steps. You can combine all of this together using LINQ extensions:
string result = "," + string.Join(",", input.Split(',').Select(s => s.Trim())) + ",";
This takes the input, splits it on the comma delimiter, then for each item in the list executes a lambda expression s => s.Trim(), which selects the trimmed version of the string for each element. This resulting enumerable is then passed back into string.Join(), and then we add the two commas at the start and end. It has the same function as the above steps, but does it one line.

Try this:
var input = "one man sitting with girl , baby girl , Smiling girl";
var output = string.Join(",", input.Split(',').Select(x => x.Trim()));
output = string.Concat(",", output, ",");

This should work:
string test = "one man sitting with girl , baby girl , Smiling girl";
Regex regex = new Regex(#"\s+,\s+");
string result = regex.Replace(test, ",");

Split your string and join it again by removing the white-spaces:
var input = "one man sitting with girl , baby girl , Smiling girl";
var output = string.Join(",", input.Split(',').Select(x => x.Trim()));
// If you wanna enclose it with commas
output = string.Format(",{0},",output);

Related

Splitting a string up and joining it back together in reverse order

I want to be able to take a sentence and split it and change the positioning of the words to put the sentence into reverse, there is no set amount of words in the sentence.
Example 1:
Input: "This is a test"
Output: "test a is This"
Example 2:
Input: "Hello World"
Output: "World Hello"
I have been trying for a while now, all I have working is
var stringreversed = stringinput.Split(" ");
But I have no idea where to go from here.
Use String.Split() to split the string, then use Array.Reverse() to reverse the resulting array:
var input = "This is a test";
// Split defaults to splitting on whitespace when you don't supply any arguments
var words = input.Split();
// Reverse the order of the words
Array.Reverse(words);
// Turn back into a string
var reversed = String.Join(" ", words);
These actions are equal. You can use different function steps or link them all together:
var s = "This is a string";
var split = s.Split(' ');
var reversed = split.Reverse();
var joined = string.Join(' ', reversed);
Console.WriteLine(joined); // output: "string a is This"
var allAtOnce = string.Join(' ', s.Split(' ').Reverse());
Console.WriteLine(allAtOnce); // output: "string a is This"
Good luck.

Manual string split in C#

In my code, I am attempting to manipulate a string:
Some text - 04.09.1996 - 40-18
I'd like to split this into three substrings: Some text, 04.09.1996, and 40-18.
When I use the Split method with a hyphen as a separator, the return value is an array of four strings: Some text, 04.09.1996, 40, and 18. How can I make this code work as described above?
You should just split with spaces around -:
.Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);
See C# demo
var res = "Some text - 04.09.1996 - 40-18".Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in res)
Console.WriteLine(s);
Result:
Some text
04.09.1996
40-18
Use this overload of string split to only get 3 parts:
var s = "Some text - 04.09.1996 - 40-18";
var parts = s.Split(new[] { '-' }, 3);
I'm assuming you also want to trim the spaces too:
var parts = s.Split(new[] { '-' }, 3)
.Select(p => p.Trim());
I would be wary of "-" or " - " appearing in "Some text", as I assume that you are interested in that as a place holder. If you are certain that "Some text" will not contain "-" than the other answers here are good, simple and readable. Otherwise we need to rely on something that we know is constant about the string. It looks to me like the thing that is constant is the last 3 hyphens. So I would try split on "-" and put the last pair back together like
string input = "Some text - 04.09.1996 - 40-18";
string[] foo = input.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
int length = foo.Length;
string[] bar = new string[3];
//put "some text" back together
for(int i=0; i< length - 3;i++)
{
bar[0] += foo[i];
}
bar[1] = foo[length - 3];
bar[2] = foo[length - 2] + "-" + foo[length - 1];
In current case you can use Split with extra space like
string.Split(" - ")
In term of "good practice" can't recommend this solution.
I am replaced character sequence '--------------------' in your string to special character "&" like below. and then split using special character "&"
string str = "Hello, my- name -------------------- is Philip J. Fry -------------------- and i like cartoons".Replace("--------------------","&");
string[] ss=str.Split('&');
string result=ss[0] + "," + ss[1]+ "," +ss[2];
then output string looks like "Hello, my- name, is Philip J. Fry, and i like cartoons"

C# Replace Everything before the first Space

I need to remove everything in a string before the first occurrence of a space.
Every string starts with a number and followed by a space
Replace the number and the space, thus leaving the rest of the string in tact
For Example:
22 The cats of India
4 Royal Highness
562 Eating Potatoes
42 Biscuits in the 2nd fridge
2564 Niagara Falls at 2 PM
I just need:
The cats of India
Royal Highness
Eating Potatoes
Biscuits in the 2nd fridge
Niagara Falls at 2 PM
Basically remove every number before the first space, including the first space.
I tried this:
foreach (string line in lines)
{
string newline = line.Trim().Remove(0, line.IndexOf(' ') + 1);
}
This works for numbers below 10. After it hits 2 digits, it doesn't work properly.
How should I change my code?
If you want to make sure you only match digits at the beginning of the string, you can use the following regex:
^\d+\p{Zs}
See demo
Declare it like:
public static readonly Regex rx = new Regex(#"^\d+\p{Zs}", RegexOptions.Compiled);
The ^\d+\p{Zs} regex means: one or more digits at the start of the string followed with 1 whitespace.
And then use it like
string newline = rx.Replace(line, string.Empty);
EDIT: To make sure the line has no leading whitespace, we can add .Trim() to strip it like:
Regex rx = new Regex(#"^\d+\p{Zs}", RegexOptions.Compiled);
string newline = rx.Replace(line.Trim(), string.Empty);
I know you already found a resolution to your issue. But I am going to explain why your code didn't work in the first place.
Your data has extra spaces which is why you are trimming it: line.Trim(). But the real problem lies in the the following statement:
string newline = line.Trim().Remove(0, line.IndexOf(' ') + 1);
You are making the assumption about the order of the operation and the fact that string data type is not immutable. When the operation of Trim() function is complete it returns a whole new string which is used in the Remove() operation. But the IndexOf() function is done on the original line of data.
So the correct line of code would be the following:
foreach (string line in lines)
{
// trim the line first
var temp = line.Trim();
// now perform all operation on the new temporary string
string newline = temp.Remove(0, temp.IndexOf(' ') + 1);
// debugging purpose
Console.WriteLine(newline);
}
Another solution:
var lines = new string[]
{
"22 The cats of India",
"4 Royal Highness",
"562 Eating Potatoes",
"42 Biscuits in the 2nd fridge",
"2564 Niagara Falls at 2 PM"
};
foreach (var line in lines)
{
var newLine = string.Join(" ", line.Split(' ').Skip(1));
}
Use a regex like so:
string newline = Regex.Replace(line, #"^\s*\d+\s*", "");
This will remove numbers only, not other text before the first space.
This is what you are looking for
foreach (string line in lines)
{
string newline = line.Replace(line.Split(new Char[]{' '})[0] + ' ',string.Empty);
}
UPDATE
string search=line.Split(new Char[]{' '})[0];
int pos=line.indexOf(search);
string newline = line.Substring(0, pos) + string.Empty + line.Substring(pos + search.Length);
FULL CODE
using System;
public class Program
{
public static void Main()
{
var lines = new string[]
{
"22 The cats of India",
"4 Royal Highness",
"562 Eating Potatoes",
"42 Biscuits in the 2nd fridge",
"2 Niagara Falls at 2 PM"
};
foreach(string line in lines){
string search=line.Split(new Char[]{' '})[0];
int pos=line.IndexOf(search);
string newline = line.Substring(0, pos) + string.Empty + line.Substring(pos + search.Length);
Console.WriteLine(newline);
}
}
}

Auto-numbering each line in textbox

I want to auto number each line that a user puts into a textbox and display the result in another textbox.
Turn this
blah blah blah
some stuff to be numbered
more stuff to number
to this
1 blah blah blah
2 some stuff to be numbered
3 more stuff to number
so far I have
output.Text = Regex.Replace(input.Text, input.Text, #"{1,}+");
But this is replacing all text with {1,}
I cant seem to figure out how to loop each line back after placing a number and a space.
(I am new to c#)
Any suggestions?
It might be simpler to implement a non-Regex solution:
var numberedLines = input.Text
.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
.Select ((line, index) => (index + 1) + " " + line)
.ToArray();
var result = string.Join(Environment.NewLine, numberedLines);
output.Text = result;
The first line uses string.Split() to split up the string around line returns into an array. Then I use LINQ .Select method to apply a function to each element in the array - in this case, adding line number and space at the beginning of each line (index + 1 is necessary because the index values are 0-based). Then I use string.Join method to put the array back together into a single string.
Demo: http://ideone.com/DrFTfl
It can actually be done with a Regular Expression if you use a MatchEvaluator delegate to apply the line numbering:
var index = 1;
output.Text = Regex.Replace(input.Text, "^",
(Match m) => (index++).ToString() + " ",
RegexOptions.Multiline);
The pattern ^ typically matches the beginning of an expression. However, with RegexOptions.Multiline, it matches the beginning of each line. Then for replacement, I use a delegate (anonymous function) that adds # + space to the beginning of the line, and then increments the index counter for the next row.
Demo: http://ideone.com/9LD0ZY
Why not just split by \r\n, concatenate each line of the string[] with an incremented number and a space, and then join by \r\n ?
If you're new to C# lets keep it as simple as possible.
By the looks of it you already have all your strings. So it boils down to this:
// store all lines in a list
// ...
var list = new List<string> {"blah", "blah2", "and some more blah"};
var list2 = new List<string>();
var i = 1;
foreach (var str in list)
{
list2.Add(string.Format("{0} {1}", i, str));
i++;
}
// write contents of list2 back to wherever you want them visualized

String concatenation using C#

I've a input string:
"risk management, portfolio management, investment planning"
How do I convert this string into:
"risk management" + "portfolio management" + "investment planning"
Thanks.
Split and Trim
// include linq library like this:
// using System.Linq;
// then
"test1, test2".Split(',').Select(o => o.Trim());
or
"test1, test2".Split(',').Select(o => o.Trim()).ToArray(); // returns array
and
"test1, test2".Split(',').Select(o => "\"" + o.Trim() + "\"")
.Aggregate((s1, s2) => s1 + " + " + s2);
// returns a string: "test1" + "test2"
Use the Split() method:
string[] phrases = s.Split(',');
Now you have a string array of each comma separated value.
To remove the spaces, use the Trim() method on each string (thanks John Feminella)
You can't use String.Split() in your case because you have a comma, then a space. So your strings will look like { "risk management", " portfolio management", " investment planning" }. Instead, use Regex.Split:
string[] investmentServices = Regex.Split(inputString, ", ");
var results = from s in string.Split("risk management, portfolio management, investment planning", new char[] { ',' })
select s.Trim();
Your question is not clear on whether you want to replace the ',' for '+' or just a simple split.
Here are the 2 possibilities:
string s = "risk management, portfolio management, investment planning";
string transformedString = s.Replace(", ", "\" + \"");
string[] parts = s.Split(new [] {", "}, StringSplitOptions.None);
If you want to split the input, you can use string.Split, using comma as a delimiter or , even better ", " for taking into account the space after comma,
string[] array = inputString.Split(", ");
However, you can be wanting to replace the comma inside the string for a plus sign, this is how you could be achieving that also:
inputString = inputString.Replace(", ", "\" + \"");
It actually looks like you're trying to perform a split, rather than concatenation.
If you're looking to take that input string and convert it into three strings containing "risk management", "portfolio management", and "investment planning", then use string.Split(inputString, ','), then trim each string from the resulting array when you use it.
It is not very clear what you mean. If you need to access the CSV values then this will output each value separately...
string input = "risk management, portfolio management, investment planning";
string[] words = text.Split(new Char[] {','});
foreach(string word in words)
{
Console.WriteLine(word.Trim());
}
//risk management
//portfolio management
//investment planning
Reply to Jhonny D. Cano
(Sorry, don't have 50 rep for a comment.)
Your first recommendation
string[] array = inputString.Split(", ");
Doesn't work because you can't split on a string. The closest possible overload is a char[], so you would have to write it as...
string[] array = inputString.Split(",
".ToCharArray());

Categories

Resources