Spliting a string into two words using while - c#

string givenstring,outputString="";
int i, j = 0;
Console.WriteLine("Enter the string");
givenstring = Console.ReadLine();
i = (givenstring.Length) / 2;
while (j < i)
{
outputString += givenstring[j];
j++;
}
Console.WriteLine(outputString);
outputString = string.Empty;
while (i < givenstring.Length)
{
outputString += givenstring[i];
i++;
}
Console.WriteLine(outputString);
Here I split the string into two string.
For example, input:
Helloworld
output:
Hello world.
But now I need the output:
dlrow olleH

The question is a vague one. If you need put all the words in the string in reversed order, e.g.
"This is a test string" -> "String test a is this"
then you can do
String source = "This is a test string";
String result = String.Join(" ", source
.Split(' ')
.Reverse()
.Select((item, index) => index > 0 ? item.ToLower() : ToNameCase(item)));
// "String test a is this"
Console.WriteLine(result);
where ToNameCase() is something like this:
private static String ToNameCase(String source) {
if (String.IsNullOrEmpty(source))
return source;
StringBuilder sb = new StringBuilder(source.Length);
sb.Append(Char.ToUpper(source[0]));
sb.Append(source.Substring(1));
return sb.ToString();
}
Edit: if you don't pay attention to case, i.e.
"This is a test string" -> "string test a is This"
you can simplify the solution into just
String source = "This is a test string";
String result = String.Join(" ", source
.Split(' ')
.Reverse());
// "string test a is This"
Console.WriteLine(result);
Edit 2: If you want to split the text into range chunks with equal lengths (with possible exception of the last chunk), and then reverse them:
String source = "HelloWorld";
int range = 2; // we want 2 chunks ("Hello" and "World")
String result = String.Join(" ", Enumerable
.Range(0, range)
.Select(index => index == range - 1 ?
source.Substring(source.Length / range * index) :
source.Substring(source.Length / range * index, source.Length / range))
.Reverse()); // remove ".Reverse()" and you will get "Hello World"
// "World Hello"
Console.WriteLine(result);

Use Aggregate like this:
string reversed = arr.Aggregate((workingSentence, next) => next + " " + workingSentence);
Console.WriteLine(reversed);
I just modify your code. It should be look like this now:
string givenstring, outputString = "";
int i, j = 0;
string[] arr = new string[2];
Console.WriteLine("Enter the string");
givenstring = Console.ReadLine();
i = (givenstring.Length) / 2;
while (j < i)
{
outputString += givenstring[j];
j++;
}
Console.Write("Input -> " + outputString + " ");//hello world
arr[0] = outputString;
outputString = string.Empty;
while (i < givenstring.Length)
{
outputString += givenstring[i];
i++;
}
arr[1] = outputString;
Console.WriteLine(outputString);
string reversed = arr.Aggregate((workingSentence, next) => next + " " + workingSentence);
Console.WriteLine("output -> " + reversed);//world hello
Console.WriteLine("output -> " + ReverseString(reversed));//olleh dlrow
Console.ReadLine();
Edit: As a better solution I removed redundant code. Check this:
static void Main(string[] args)
{
var arr = new string[2];
Console.WriteLine("Enter the string");
var givenstring = Console.ReadLine();
if (givenstring != null)
{
int i = (givenstring.Length) / 2;
arr[0] = givenstring.Substring(0 , i);
arr[1] = givenstring.Substring(i, givenstring.Length - i);
}
Console.WriteLine("Input -> " + arr[0] + " " + arr[1]);//hello world
var reversed = arr.Aggregate((workingSentence, next) => next + " " + workingSentence);
Console.WriteLine("output -> " + reversed);//world hello
Console.WriteLine("output -> " + ReverseString(reversed));//olleh dlrow
Console.ReadLine();
}
static string ReverseString(string str)
{
char[] chars = str.ToCharArray();
char[] result = new char[chars.Length];
for (int i = 0, j = str.Length - 1; i < str.Length; i++, j--)
{
result[i] = chars[j];
}
return new string(result);
}

Try this
string s = "Helloworld someother string";
var str = s.Split(' ')[0];
int i = str.Length/2;
Console.WriteLine(str.Substring(i) + " " + str.Substring(0,i));
//or
Console.WriteLine(string.Join(" ",str.Substring(i),str.Substring(0,i)));

You can use mixture of Skipwhile, Concat and Take methods :
string s = "Helloworld";
int half = s.Length / 2;
s = new String(s.SkipWhile((ss, i) => i < half)
.Concat(" ").Concat(s.Take(half)).ToArray());
Console.WriteLine(s);
Output : world Hello
OR you can simply concat substrings :
string givenstring,outputString="";
Console.WriteLine("Enter the string");
givenstring = Console.ReadLine();
int half = givenstring.Length / 2;
givenstring = givenstring.Substring(half , half) + " " + givenstring.Substring(0, half );
(I assume you've string with just two words because you didn't provide an example of a test string you work with other then Helloworld)...

Related

C# merge lines of strings into groups of 3 at a time

I have a string like this (including newlines)
A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,
I am trying to make this string to look like this:
A2,10.22,-57,
A,10.23,-68,
A2,10.24,-60,
LB,10.25,-62,
I need to join string in every 3 line i have tried :
int numLines = a.Split('\n').Length;
for (int i = 0; i < numLines; i += 3)
{
richTextBox1.Text = a.Replace("\n", "");
}
But it is not working for me. Please help me out
You can also approach this with LINQ, by using the index overload of .Select to retain a running count of the line numbers, and then to group them into groups of 3 - I've used integer division to Floor the line index, 3 at a time, but there are likely other suitable ways.
var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
.GroupBy(x => x.Index);
Where each item in the groups above will be IEnumerable<(Index, Value)>.
You'll also need to be wary of newlines - these may be \r\n in Windows, not just the \n you've indicated.
Here's an example:
var a =
#"A2,
10.22,
-57,
A,
10.23,
-68,
A2,
10.24,
-60,
LB,
10.25,
-62,";
var values = a.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
var groups = values.Select((s, idx) => (Index: idx / 3, Value: s))
.GroupBy(x => x.Index);
foreach (var grp in groups)
{
Console.WriteLine(string.Join("", grp.Select(x => x.Value)));
}
Since you've already got commas at the end of each string (including the last one), there's no need to add another separator.
Output:
A2,10.22,-57,
A,10.23,-68,
A2,10.24,-60,
LB,10.25,-62,
Why not use the array that the split gives you instead?
var newArr = a.Split('\n');
for (int i = 0; i < newArr.Length; i += 3)
{
richTextBox1.Text = newArr[i] + newArr[i + 1] + newArr[i + 2];
}
Just don't forget to check the length of the arrays so that you don't get a IndexOutOfRange Exception.
I'm assuming that the input is actually coming from a file here.
var file = //file path
var sb = new StringBuilder();
var lineNum = 1;
var output = string.Empty;
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (lineNum % 3 == 0)
{
output += sb.ToString() + "\n";
sb.Clear();
}
else
sb.Append(line);
lineNum++;
}
}
richTextBox1.Text = output;
Try this solution which is a combination of linq and for loop
var result = "";
var items = yourInputString.Split('\n');
for(var i=0; i<items.Count();i=i+3)
{
result += string.Join(",",items.Skip(i).Take(3))+"\n";
}
static void Main(string[] args)
{
var Lines = System.IO.File.ReadAllLines("input.txt");
var Result = new StringBuilder();
var SB = new StringBuilder();
for (var i = 0; i < Lines.Length; i++)
{
SB.Append(Lines[i]);
if ((i+1) % 3 == 0)
{
Result.Append($"{SB.ToString()}{Environment.NewLine}");
SB.Clear();
}
}
System.IO.File.WriteAllText("output.txt", Result.ToString());
}
Try to use Aggregate function
var outPutList = data.Replace("\r", string.Empty).Replace("\n", string.Empty).Split(",").Aggregate(new StringBuilder(""), (x, y) =>
{
if (double.TryParse(y, out double parsedValue))
x.Append(" " + parsedValue);
else
{
x.Append(Environment.NewLine);
x.Append(y.Trim());
}
return x;
});
richTextBox1.Text = outPutList.ToString();
Here is the output
try this works
private void button1_Click(object sender, EventArgs e)
{
//put your string in a textxbox with multiline property set to true
string[] s = textBox1.Text.Replace("\r", "").Replace("\n", "").Split(',');
string r = "";
for (int i = 0; i < s.Length; i++)
{
r = r + s[i] + ",";
if ((i + 1) % 3 == 0)
r = r + "+";
}
if (r.Substring(r.Length - 1, 1) == ",")
r = r.Substring(0, r.Length - 1);
if (r.Substring(r.Length - 1, 1) == "+")
r = r.Substring(0, r.Length - 1);
string[] finalArrayString = r.Trim().Split('+');
//just for show the result
textBox1.Text = "";
for (int i = 0; i < finalArrayString.Length; i++)
textBox1.Text = textBox1.Text + finalArrayString[i] + "\r\n";
}
hope it helps you

c# Reversing words in a string using single loop without using reverse function and stack

I have tried writing the logic for reversing each word in a string with single loop but I didn't get it to work. Can you please provide the logic to reverse every word in a string using single loop and without using reverse function.
Input:
Welcome to the world
Output:
emocleW ot eht dlrow
My Logic with two loops:
class Program
{
static void Main(string[] args)
{
string input = string.Empty;
input = Console.ReadLine();
string[] strarr=input.Split(' ');
StringBuilder sb = new StringBuilder();
foreach (string str in strarr)
{
sb.Append(fnReverse(str));
sb.Append(' ');
}
Console.WriteLine(sb);
Console.Read();
}
public static string fnReverse(string str)
{
string result = string.Empty;
for (int i = str.Length-1; i >= 0; i--)
result += str[i];
return result;
}
}
string strIn = "Welcome to the world";
string strTmp = "";
string strOut = "";
for (int i=strIn.Length-1; i>-1; i--)
{
if (strIn[i] == ' ')
{
strOut = strTmp + " " + strOut;
strTmp = "";
}
else
{
strTmp += strIn[i];
}
}
strOut = strTmp + " " + strOut;
Gives the result "emocleW ot eht dlrow"
string input = Console.ReadLine();
string result = "";
string tmp = "";
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ' ')
{
result = tmp + " " + result;
tmp = "";
}
else
tmp += input[i];
}
result = tmp + " " + result;
Console.WriteLine(result);
Here is the DEMO

Split and append a string?

Right now I take in a string like this "112233 112233 112233 112233", and I split it into an array like this:
string text = ProcessString("112233 112233");
string[] dates = text.Split(' ');
And that works great, but I want to use string builder to build my string so they would end up like 11-22-33 11-22-33 etc.
So I did try this:
static string ProcessString(string input)
{
StringBuilder buffer = new StringBuilder(input.Length * 3 / 2);
for (int i = 0; i < input.Length; i++)
{
if ((i > 0) & (i % 2 == 0))
buffer.Append("-");
buffer.Append(input[i]);
}
return buffer.ToString();
}
It works, but it does not match the expected output of:
11-22-33
11-22-33
My current output is:
11-22-33-
1-12-23-3
-11-22-33
What can I do to fix this?
You can process a single string simply by iterating and collecting size-2 substrings of the string, and then joining them by the - character:
string s = "112233";
List<string> parts = new List<string>(s.Length / 2);
for (int i = 0; i < s.Length; i += 2)
parts.Add(s.Substring(i, 2));
Console.WriteLine(string.Join("-", parts)); // 11-22-33
So, for your full problem, you could do this:
static string ProcessString(string input)
{
var segments = input.Split(' ').Select(s =>
{
List<string> parts = new List<string>(s.Length / 2);
for (int i = 0; i < s.Length; i += 2)
parts.Add(s.Substring(i, 2));
return string.Join("-", parts);
});
return string.Join(" ", segments);
}
How about regex:
string s = "112233";
string pattern = #"\d{2}\B";
string result = Regex.Replace(s, pattern, m => m.Value + "-");
Can i offer you another Regex + LINQ approach?
var newDates = dates.Select(d => Regex.Replace(d, ".{2}", "$0-").Trim('-'));
string result = string.Join(" ", newDates);
But i like this extension more because it's readable and re-usable:
public static IEnumerable<String> SplitInParts(this String s, Int32 partLength)
{
if (s == null)
throw new ArgumentNullException("s");
if (partLength <= 0)
throw new ArgumentException("Part length has to be positive.", "partLength");
for (var i = 0; i < s.Length; i += partLength)
yield return s.Substring(i, Math.Min(partLength, s.Length - i));
}
Then the code is even easier:
var newDates = dates.Select(d => string.Join("-", d.SplitInParts(2)));
string result = string.Join(" ", newDates);
I have this approach :
string input = "112233 445566 778899 101010";
string[] dates = input.Split(' ');
foreach (string date in dates){
Console.WriteLine(date);
string result = date.Substring(0, 2) + '-' + date.Substring(2, 2) + "-" + date.Substring(4, 2);
Console.WriteLine(result);
}
You can use Array.ConvertAll:
string str = "112233 112233 112233 112233";
string[] dates = str.Split();
dates = Array.ConvertAll(dates, s => s.Insert(4, "-").Insert(2, "-"));
foreach (var s in dates)
Console.WriteLine(s);

split string around newline after some interval

I am trying to make some logic, but it is not ful proof yet:
string s = "1234567877y";
StringBuilder sb = new StringBuilder(s);
for (int i = 5; i <= s.Length + (s.Length / 5 ); i += 5 + (s.Length / 5) )
{
sb.Insert(i, Environment.NewLine);
}
Console.WriteLine(sb.ToString());
Console.ReadKey();
Output should be:
12345
67877
y
StringBuilder contain: "12345\r\n67877\r\ny"
But if i change input string i am not getting desired result. What i can do here or suggest some other way around.
EDIT:
if i change
string s = "1234567877y3434";
output will be
12345
67877y
3434
Another concise approach is using GroupBy:
string s = "1234567877y";
IEnumerable<string> groups = s.Select((c, index) => new{ c, index })
.GroupBy(x => x.index / 5)
.Select(xg => string.Join("", xg.Select(x => x.c)));
string result = string.Join(Environment.NewLine, groups);
Here is an approach with a StringBuilder which is more efficient:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if ((i+1) % 5 == 0)
sb.Append(s[i]).Append(Environment.NewLine);
else
sb.Append(s[i]);
}
i would do it this way :)
string s = "1234567877y3434";
for (int i = 5; i < s.Length; i += 5 + Environment.NewLine.Length)
{
s = s.Substring(0, i) + Environment.NewLine + s.Substring(i, s.Length - i);
}
EDIT: i corrected my code using the suggstestion from Chris using Environment.NewLine instead of \r\n

Break on space, textbox (specific condition)

I need to break on closest space to 30th character of texbox, and I got very good answer for that:
var x = 30;
if (textBox1.Text.Length > x)
{
var index = textBox1.Text.Select((c, i) => new {c, i}).TakeWhile(q => q.i < x).Where(q => q.c == ' ' ).Select(q => q.i).Last();
textBox1.Text = textBox1.Text.Insert(index, Environment.NewLine);
}
Only problem is that I need to exclude from counting characters like "#A", "#B", because they are used for text formatting.
Although perhaps not the cleanest solution. If you simply count on # (or perform a regex to detect patterns) and add that number to x (30) like:
int paramCount = test.Where(c => c == '#').Count();
var index = test.Select((c, i) => new { c, i })
.TakeWhile(q => q.i < x + paramCount)
.Where(q => q.c == ' ')
.Select(q => q.i)
.Last();
edit
In order to make sure your count only counts the first 30 characters (excluding '#'), you can perform an aggregate in advance:
int paramCount = test.Select((c, i) => new { c, i })
.Aggregate(0, (count, s) => s.c == '#' && s.i < x + count ? count + 1 : count);
textBox1.Text.Replace("#A", "").Replace("#B", "")...
You can try the code below.
string sTemp = textBox1.Text.Substring(0, 30);
sTemp = sTemp.Replace(" #A ", "");
sTemp = sTemp.Replace("#A ", "");
sTemp = sTemp.Replace(" #A", "");
sTemp = sTemp.Replace("#A", "");
sTemp = sTemp.Replace(" #B ", "");
sTemp = sTemp.Replace("#B ", "");
sTemp = sTemp.Replace(" #B", "");
sTemp = sTemp.Replace("#B", "");
int numberOfLeak = 30 - sTemp.Length;
var x = 30 + numberOfLeak;
if (textBox1.Text.Length > x)
{
textBox1.Text = textBox1.Text.Insert(x, Environment.NewLine);
}
string oriText = textBox1.Text;//Original text that you input
int charPerLine = 30;//Number of character per line
string sKeyword = "#A|#B";//You can add more template here, the separator is "|"
string[] arrKeyword = sKeyword.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
ArrayList arrListKeyword = new ArrayList();
for (int i = 0; i < arrKeyword.Length; i++)
{
arrListKeyword.Add(" " + arrKeyword[i] + " ");
arrListKeyword.Add(arrKeyword[i] + " ");
arrListKeyword.Add(" " + arrKeyword[i]);
arrListKeyword.Add(arrKeyword[i]);
}
int nextIndex = 0;
while (true)
{
//Check if the sub string after the NewLine has enough length
if (charPerLine < oriText.Substring(nextIndex).Length)
{
string sSubString = oriText.Substring(nextIndex, charPerLine);
//Replace all keywords with the blank
for (int i = 0; i < arrListKeyword.Count; i++)
{
sSubString = sSubString.Replace(arrListKeyword[i].ToString(), "");
}
int numberOfLeak = charPerLine - sSubString.Length;
int newLineIndex = nextIndex + charPerLine + numberOfLeak;//find the index to insert NewLine
oriText = oriText.Insert(newLineIndex, Environment.NewLine);//Insert NewLine
nextIndex = newLineIndex + Environment.NewLine.Length;//Environment.NewLine cost 2 in length
}
else
{
break;
}
}
textBox1.Text = oriText;

Categories

Resources