Reputation: 223
i have following piece of code with me iam spliting the words using only one space and the output is
output:
when ambition ends happiness begins
But i want split the words after two spaces i mean my output should be like this:
when ambition ends happiness begins
string vj = "when ambiton ends happiness begins";
List<string> k = new List<string>();
char ch = ' ';
string[] arr = vj.Split(ch);
foreach (string r in arr)
{
Response.Write(r + "<br/>");
}
Upvotes: 0
Views: 177
Reputation: 13151
string vj = "when ambiton ends happiness begins";
List<string> k = new List<string>();
char ch = ' ';
string[] arr = vj.Split(ch);
bool flag=false;
foreach (string r in arr)
{
if(flag)
{
Response.Write(r + "<br/>");
flag=false;
}
else
{
Response.Write(r + " ");
flag=true;
}
}
The above is good for the case you specified (skipping a single space).
Though not necessary, but if you want it all wrapped up, Here :
string myString = "when ambiton ends happiness begins";
bool flag=false;
foreach (string item in myString.Split(ch))
Response.Write(item + flag=!flag?" ":"<br/>");
Upvotes: 0
Reputation: 113402
Here's a solution with regular expressions:
// Loosely: a word, followed by another word if available
Regex regex = new Regex(@"\S+( \S+)?");
string[] splits = regex.Matches(inputText)
.Cast<Match>()
.Select(match => match.Value)
.ToArray();
Upvotes: 2
Reputation: 5880
You can just add a bool indicating whether or not you should add "/br", call it breakLine.
Now at each iteration check if it's true - if so add "/br", otherwise don't. finally negate it at each iteration.
Implementation is left as an exercise (-:
Upvotes: 0
Reputation: 101150
Upvotes: 0
Reputation: 26227
Split it like you do right now, then loop the resulting array and join them all up using a standard for
loop.
Upvotes: 1
Reputation: 499002
As this is marked homework, I will give a hint:
Upvotes: 2
Reputation: 2340
You're gonna have to go manual on this one, searching for the space-character in the string, and keeping a counter. You'll have to remember the indices of the space-characters you'll want to split from, and use the .Substring(startindex, length) method for extracting the separate parts.
Upvotes: 0