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());
Related
I have the following string:
string testString = ",,,The,,,boy,,,kicked,,,the,,ball";
I want to remove the unwanted commas and have the sentence as this (simply printed to the console):
The boy kicked the ball
I tried the below code:
string testString = ",,,The,,,boy,,,kicked,,,the,,ball";
string manipulatedString = testString.Replace(",", " "); //line 2
Console.WriteLine(manipulatedString.Trim() + "\n");
string result = Regex.Replace(manipulatedString, " ", " ");
Console.WriteLine(result.TrimStart());
However, I end up with a result with double whitespaces as so:
The boy kicked the ball
It kind of makes sense why I am getting such an anomalous output because in line 2 I am saying that for every comma (,) character, replace that with whitespace and it will do that for every occurrence.
What's the best way to solve this?
This is a simple solution using Split and Join
string testString = ",,,The,,,boy,,,kicked,,,the,,ball";
var splitted = testString.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
string result = string.Join(" ", splitted);
Console.WriteLine(result);
You could use regex to replace the pattern ,+ (one or more occurrences of a comma) by a whitespace.
var replacedString = Regex.Replace(testString, ",+", " ").Trim();
Added Trim to remove white spaces at beginning/end as I assume you want to remove them.
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"
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);
Trim() Function Not Working Please Help its not trimming the white space.
string samplestring = "172-6573-4955";
string[] array = samplestring .Split('-');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
array[1] = restOfArray.Trim(); // providing value "6573 4955"
The scenario is I am splitting string and merging 2nd and last index into one but it's merging with white spaces.
Trim() removes whitespace from the front and back of a string, not in the middle. The whitespaces in the middle are being inserted by the " " provided as the parameter to Join() method. You could provide string.empty instead.
Trim is used to remove all leading and trailing white-space. And you want to trim the white space from middle. You may try like this:
string restOfArray = string.Join("", array.Skip(1));
or better:
string restOfArray = string.Join(string.Empty, array.Skip(1));
instead of
string restOfArray = string.Join(" ", array.Skip(1));
Trim is working as expected. Taken from String.Trim Method:
Removes all leading and trailing white-space characters from the
current String object.
The possible solutions for you are :
string restOfArray = string.Join(string.Empty, array.Skip(1));
Or
array[1] = restOfArray.Replace(" ", string.Empty).Trim();
To just split the first n-let from the rest use an additional array or you will end up with spurious data. And join with the correct separator you used in split(-):
string restOfArray = string.Join("-", array.Skip(1));
string[] result = new string[] { firstElem, restOfArray };
You don't need Trim().
You can simplify your code this way:
string[] splitCode(string code)
{
string[] segments;
segments = code.Split('-');
return new string[] { segments.First(), string.Join("-", segments.Skip(1)) };
}
Trim really isn't need here; you can simply split the string and join the parts you want:
string source = "172-6573-4955";
string[] splitter = new string[] {"-"};
string[] result;
result = source.Split(splitter, StringSplitOptions.None);
string final = (result[1] + result[2]);
Console.Write(final);
Result:
65734955
Try this:
string samplestring = "172-6573-4955";
string[] array = samplestring.Split(new char[] {'-'},2);
string result = array[1].Replace("-","");
Also, for your question about randomly putting spaces, can u pls explain "randomly" here.
I have a string,
string aString = "a,aaa,aaaa,aaaaa,,,,,";
Where i want to insert to a List..But when i do using the following method,
List<string> aList = new List<string>();
aList.AddRange(aString.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
MessageBox.Show(aList.Count.ToString());
I get the count as only 4, But there are actually 8 elements even the final characters in between the (,) sign is blank.
But if i pass the string as shown below,
string aString = "a,aaa,aaaa,aaaaa, , , , ,";
It will be shown as 8 elements..Please help me on this, the default way thw program retrieves the string is like so,
a,aaa,aaaa,aaaaa,,,,,
Please help on this one, It would be great if i could add spaces to the empty area or any other way so that i could add all these characters in between (,) sign to the list.. even the blank areas. Thank you :)
Don't use StringSplitOptions.RemoveEmptyEntries
string aString = "a,aaa,aaaa,aaaaa,,,,,";
var newStr = String.Join(", ", aString.Split(','));
I think you must remove StringSplitOptions.RemoveEmptyEntries
aList.AddRange(aString.Replace(",,", ", ,").Split(new string[] { "," }));
You can just Replace the space before split it.
aList.AddRange(aString.Replace(" ", "").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));