This question already has answers here:
Reverse the ordering of words in a string
(48 answers)
Closed 1 year ago.
I want to reverse an array with console.ReadLine(), but I'm stuck.
Here is statement of problem.
Give an array of 10 natural numbers. Displays the numbers in the string in reverse order.
The numbers in the string are given on a single line and are separated by a space. The application will display the numbers on a single line, separated by a space between them.
Example:
For input data:
1 2 3 4 5 6 7 8 9 10
The console will display:
10 9 8 7 6 5 4 3 2 1
here is my code:
string number = Convert.ToString(Console.ReadLine());
List<string> originalList = new List<string>();
for (int i = 0; i < 1; i++)
{
originalList.Add(number);
}
foreach (string item in originalList)
{
Console.Write(item + " ");
}
originalList.Reverse();
foreach (string item in originalList)
{
Console.WriteLine(item + " ");
}
Console.WriteLine();
The numbers in the string are given on a single line and are separated by a space.
The following code is incorrect because Console.ReadLine does not stop reading when it encounters whitespace. It will consume the entire input as one entry in originalList.
string number = Convert.ToString(Console.ReadLine());
List<string> originalList = new List<string>();
for (int i = 0; i < 1; i++)
{
originalList.Add(number);
}
// originalList is now [ "1 2 3..." ];
Instead, you should look at String.Split.
string input = Console.ReadLine();
List<string> originalList = input.Split(' ').ToList();
// originalList is now [ "1", "2", "3", ... ];
You can now use List.Reverse and String.Join to get your output.
originalList.Reverse();
string output = string.Join(' ', originalList);
Console.WriteLine(output);
Need either string.Split (' ') or a for loop or a while loop
Using string.Split (' ')
string [] splitArray = number.Split (' ');
for (int i = 0; i < splitArray.Length; i++)
{
originalList.Add(splitArray [i]);
}
//rest of the code would be same
For loop
String readvalues="";
for (int i=0;i <number.Length;i++)
{
if (i==number Length-1)
{
readvalues += number [i];
}
if (number[i]==" " || i==number.Length-1)
{
originalList.Add (readvalues);
readvalues="";
}
else
{
readvalues += number [i];
}
}
//rest of the code would be same
While loop
int index=0;
String readvalues="";
while (index < number.Length)
{
if (index==number.Length-1)
{
readvalues += number [index];
}
if (number[index]==" " ||index==number.Length-1)
{
originalList.Add (readvalues);
readvalues="";
}
else
{
readvalues += number [index];
}
index++;
}
//rest of the code would be same
I think, I have a solution for you, what you exactly ask for. Please check the code and let me know =>
void Test()
{
string number = Convert.ToString(Console.ReadLine());
List<string> originalList = new List<string>();
if(!string.IsNullOrEmpty(number) && !string.IsNullOrWhiteSpace(number) )
{
originalList=number.Split(" ").ToList();
originalList.Reverse();
Console.WriteLine(string.Join(" ", originalList));
}
}
Note : Use those three namespaces using System;,using System.Linq;,using System.Collections.Generic;
You can try querying the initial string with a help of Linq (Reverse):
Split string into items
Reverse these items
Join items back into string
Code:
using System.Linq;
...
// For Test (comment it out for release)
string source = "1 2 3 4 5 6 7 8 9 10";
// Uncomment for release
// string source = Console.ReadLine();
string result = string.Join(" ", source
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Reverse());
Console.WriteLine(result);
Outcome:
10 9 8 7 6 5 4 3 2 1
Related
I'm trying to convert all the number from a list of strings to float. I'm not sure why all the items from the list are char, and it converts every single digit to char instead of converting the number until space. Below is the code. If the first input is 2, it will create 2 lists, let's say 12 23 33 and 22 33 44.
From list 1, I need mm to be 12/23/33 instead of 1/2/2/3/3/3
int nrMagazine = Convert.ToInt32(Console.ReadLine());
List<String> mag = new List<String>();
string prop = "";
for(int i = 0; i < nrMagazine;i++)
{
string profitTrimestre = Console.ReadLine();
profitTrimestre.Split();
mag.Add(profitTrimestre);
//cel mai profitabil trimestru,trimestru 1 = m[0],1=m[1]
//cel mai profitabil magazin,mag 1,2,3,4,n
}
foreach(string m in mag)
{
foreach(string mm in m)
{
Console.WriteLine(mm);
}
}
There are multiple problems in your current code.
I m not sure why all the items from the list are char
Because you have another loop for string which implicitly using enumerator iterates the string by character. You should be able to convert to float by using Convert class :
foreach(string m in mag)
{
var number = Convert.ToDouble(m);
}
Secondly if numbers are space delimited then use Split overload that takes character to use for splitting :
var splitted = profitTrimestre.Split(new char[]{' '}, StringSplitOption.RemoveEmptyEntries);
and then loop :
foreach(var item in splitted)
mag.Add(item);
you can try this
public static void Main(string[] args)
{
var text = Console.ReadLine();
var strings = text.Split(' '); // This splits the 11 22 33 to three string values.
var numbers = strings.Select(a =>
{
if (float.TryParse(a, out float number))
return number;
return 0;
}).ToList(); // This converts 3 strings to 3 float
}
Or you can try the shortest version (thanks to Prasad Telkikar)
public static void Main(string[] args)
{
var numbers = Array.ConvertAll(Console.ReadLine().Split(' '), x => float.TryParse(x, out float number) ? number : 0);
}
Maybe you just need to split your line on spaces instead and actually assign the split value to mag?
string[] mag = profitTrimestre.Split(' ');
Then you should be able to loop over each string in that list with just one foreach:
foreach(string m in mag)
{
Console.WriteLine(m);
}
If you want to convert the individual string parts to Doubles, you can do that like this:
double d = double.Parse(m);
You can also do it like this, if you want to avoid exceptions if the strings aren't valid double representations:
double.TryParse(m, out double d);
profitTrimestre.Split(); will return an array, which currently you're doing nothing with it. Try change to this instead:
Console.WriteLine("Insert the number of lists: ");
if(int.TryParse(Console.ReadLine(),out int nrMagazine)) //Never trust user's inputs
{
List<string> mag = new List<string>();
for(int i = 0; i < nrMagazine;i++)
{
Console.WriteLine($"Insert List {i+1}: ");
mag.Add(Console.ReadLine());
}
foreach(string m in mag) //iterates over each input string
{
foreach(string mm in m.Split(' ')) //splits each entry and iterates over the itens
{
Console.WriteLine(mm);
if(double.TryParse(mm, out double myDouble)) //You can also pass a Culture
{
//Do something with your double
}
else
{
//Input not a double in the current culture
}
}
}
}
else
{
Console.WriteLine("The input was not an integer");
}
I guess that's what you need.
Dictionary<int, IEnumerable<float>> nrMagazine = new Dictionary<int, IEnumerable<float>>(); //creates dictionary
int.TryParse(Console.ReadLine(), out int x); //input number for iterations here
for (int i = 0; i < x; i++)
{
nrMagazine.Add(i, Console.ReadLine().Split(' ').Select(s => { float.TryParse(s, out float y); return y; })); //builds floats list and adds it to dictionary x times
}
nrMagazine.Keys.ToList().ForEach((i) => Console.WriteLine("Magazine: " + i + ", Profits: " + String.Join(", ", nrMagazine[i]))); //prints items from dictionary
This is my code. How can I edit it to show every word which is at the odd position ONLY to be reversed?
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);
Example input:
"How are you today"
to output:
"How era you yadot"
Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
You can achieve it with the help of LINQ:
var input = "hello this is a test message";
var inputWords = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var result = string.Join(" ",
inputWords.Select((w, i) =>
i % 2 == 0
? w
: new string(w.Reverse().ToArray())
));
Where w in the select is the word, and i is the index, starting at 0 for the first word. % is the modulus operator and gets the remainder. If i % 2 == 0 (i.e. i can be divided by 2 with no remainder), then the original is returned. If there is a remainder (odd) then the reversed word is returned. Finally, it's all wrapped up in a string.Join(" ", items); which turns it back into a normal string rather than an array of items.
Try it online
So far you have a string, like this:
string input = "I want to reverse all odd words (odd words only!).";
And you, naturally, want to perform the task. Now it's the main question what's an odd word?
If you mean word's position (I at position 0, want at 1 - should be reversed etc.)
then you can use regular expressions to match words and Linq to process them:
using System.Linq; // To reverse single word
using System.Text.RegularExpressions; // To match the words within the text
...
// Let's elaborate the test example: add
// 1. some punctuation - ()!. - to preserve it
// 2. different white spaces (spaces and tabulation - \t)
// to add difficulties for naive algorithms
// 3. double spaces (after "to") to mislead split based algorithms
string input = "I want to reverse all\todd words (odd words only!).";
int index = 0; // words' indexes start from zero
string result = Regex.Replace(
input,
"[A-Za-z']+", // word is letters and apostrophes
match => index++ % 2 == 0
? match.Value // Even words intact
: string.Concat(match.Value.Reverse())); // Odd words reversed
Console.WriteLine(result);
If you want to reverse the words with odd Length, i.e. I, all, odd then all you have to do is to change the condition to
match => match.Value % 2 == 0
Outcome:
I tnaw to esrever all ddo words (ddo words ylno!).
Please, notice, that the punctuation has been preserved (only words are reversed).
OP: Based on the position of a word ['How' -> 0] do not reverse; [are -> 1 odd index] Reverse
public static void Main()
{
string input = "How are you today Laken-C";
//As pointed out by #Dmitry Bychenko string input = "How are you today";
//(double space after How) leads to How are uoy today outcome
input = Regex.Replace(input, #"\s+", " ");
var inp = input.Split(' ').ToList();
for (int j = 0; j < inp.Count(); j++)
{
if(j % 2 == 1)
{
Console.Write(inp[j].Reverse().ToArray());
Console.Write(" ");
}
else
Console.Write(inp[j] + " ");
}
}
OUTPUT:
DEMO:
dotNetFiddle
try this is perfect working code..
static void Main(string[] args)
{
string orgstr = "my name is sagar";
string revstr = "";
foreach (var word in orgstr.Split(' '))
{
string temp = "";
foreach (var ch in word.ToCharArray())
{
temp = ch + temp;
}
revstr = revstr + temp + " ";
}
Console.Write(revstr);
Console.ReadKey();
}
Output: ym eman si ragas
Ok so this is one of my exercises that I can't figure out.
The input is : 1 2 3 |4 5 6 | 7 8
What i need to print out is : 7 8 4 5 6 1 2 3
What i pretty much get is : 1 2 3 4 5 6 7 8
I need you guys to help me find out what the problem may be
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApp41
{
class Program
{
static void Main(string[] args)
{
string tokens = Console.ReadLine();
List<string> list = tokens.Split('|').ToList();
List<string> listTwo = new List<string>(list.Count);
foreach (var token in list)
{
token.Split(" ");
listTwo.Add(token);
}
foreach (var token in listTwo)
{
listTwo.Remove(" ");
}
for (int i = 0; i < listTwo.Count; i++)
{
Console.Write(listTwo[i]);
}
}
}
}
Your "exercise" solution is one line to me:
string input = "1 2 3 |4 5 6 | 7 8";
string result = string.Join(" ", input.Split('|').Select(s => s.Trim()).Reverse());
Console.WriteLine(result);
but for exercise purposes, it would be better if you do it step by step, to understand more whats going on (for example):
//Split your string to string[] by given separator
string[] splitedString = input.Split('|');
//create new array to store your result values
string[] resultArray = new string[splitedString.Length];
//loop backwards through your array and store your values into new array (resultArray)
for (int i = splitedString.Length - 1, j = 0; i >= 0; i--, j++)
{
resultArray[j] = splitedString[i].Trim();
}
//Iterate through new array and construct new string from existing values,
//method Trim() is removing leading and trailing whitespaces
string result = string.Empty;
foreach (string item in resultArray)
{
result += item + " ";
}
Console.WriteLine(result.Trim());
References: MSDN String.Trim(), DotNetPerls C# Trim Strings
this may help you
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApp41
{
class Program
{
static void Main(string[] args)
{
string tokens = Console.ReadLine();
List<string> list = tokens.Split('|').ToList();
List<string> listTwo = new List<string>(list.Count);
foreach (var token in list)
{
token.Split(" ");
listTwo.Add(token);
}
foreach (var token in listTwo)
{
listTwo.Remove(" ");
}
//change this loop like this
for (int i =listTwo.Count-1 ; i >0 ; i--)
{
Console.Write(listTwo[i]);
}
}
}
}
This is one of the simple way of doing
static void Main(string[] args)
{
string tokens = "1 2 3 |4 5 6 | 7 8";
var list = tokens.Split('|');
list = list.Reverse().Select(n=> n.Trim().PadRight(n.Length,' ')).ToArray();
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i]);
}
Console.ReadLine();
}
WHAT I DID
Reverse the array which you got after splitting your input string. I used inbuilt Reverse() function. No need to code your own until compulsory. Advantage of framework and C#.
Select() is LINQ function which helps to select element from any list,array (many more but for basic understanding list and array). (It will iterate to each element though it is not a loop.)
Trmi() will remove leading and trailing space and then PadRight() will add required space to each element in array.
OUTPUT
7 8 4 5 6 1 2 3
Split your string with '|'.
Iterate through each element of array in reverse order and use
Trim().
Concatenate string with space to result, I used StringBuilder to append result, Return full string
public string GetArrayString(string token)
{
//Here you split
string[] arr = token.Split('|');
StringBuilder sb = new StringBuilder();
//Use for loop in reverse order, as you want to reverse the string
for(int i = arr.Length - 1; i >= 0; i--)
{
//Append result to stringbuilder object with " "
sb.Append(arr[i].Trim() + " ");
}
//Convert string builder object to string and return to the main function
return sb.ToString().Trim();
}
public static void Main(string[] args)
{
//Read inputs from user in your case it is 1 2 3 |4 5 6 | 7 8
string token = Console.ReadLine();
//Here function will return expected output; note you need to create instance of class otherwise assign GetArrayString method as a static
Console.WriteLine(GetArrayString(string token));
}
Output
7 8 4 5 6 1 2 3
POC : DotNetFiddler
While everyone is basically giving you a working solution, I will answer that part of your question:
I need you guys to help me find out what the problem may be
using System;
using System.Linq;
using System.Collections.Generic;
namespace ConsoleApp41
{
class Program
{
static void Main(string[] args)
{
string tokens = Console.ReadLine();
List<string> list = tokens.Split('|').ToList();
List<string> listTwo = new List<string>(list.Count);
foreach (var token in list)
{
// the following line won't do anything
// as you don't assign its result to a variable
token.Split(" ");
// so you are only adding every token from list in listTwo
listTwo.Add(token);
}
// at this point, the content of list and listTwo are the same
foreach (var token in listTwo)
{
// you are iterating through 'listTwo', and you don't even
// use 'token', so what's that foreach for?
// do you really believe 'listTwo' contains that much " "?
// as a reminder, listTwo = { "1 2 3 ", "4 5 6 ", " 7 8" }
listTwo.Remove(" ");
}
for (int i = 0; i < listTwo.Count; i++)
{
// here you just print the original 'tokens' without '|'
Console.Write(listTwo[i]);
}
}
}
}
write a loop that prints a number of lines the user entered into the text box
for example, this is using c# windows application
user inputs 10, then in another textbox counts from 0 to 10 on different lines
Result
0 \r\n
1 \r\n
2 \r\n
3 \r\n
4 \r\n
5 \r\n
6 \r\n
7 \r\n
8 \r\n
9 \r\n
10 \r\n
i have tried to incorporate a for loop and for each but it is only printing out one value, and i have to go into the array and print each iteration of the array like so textboxOutput.text = Array[0] + Array[1] , but i want it to print out all of the list without accessing the single ints in the array
private void button1_Click(object sender, EventArgs e)
{
string input = textBox1.Text;
int Number;
bool Anumber = Int32.TryParse(input, out Number);
int newNumber = Number;
int[] List = new int[newNumber];
for (int i = 0; i < List.Length; i++ )
{
List[i] = i;
//textBox2.Text =List[0] + "\r\n" + List[1] + "\r\n" + List[2];
}
foreach (int num in List)
{
textBox2.Text = num.ToString() ;
}
}
}
}
I have managed to figure out my own question
private void button1_Click(object sender, EventArgs e)
{
int OutputNumber;
bool number = Int32.TryParse(inputtxt.Text, out OutputNumber);
string[] array = new string[OutputNumber];
int put = 0;
for (int i = 0; i < array.Length; i++)
{
array[i] = put.ToString();
put++;
string result = ConvertStringArrayToString(array);
string result1 = result + OutputNumber.ToString();
outputtxt.Text = result1;
}}
static string ConvertStringArrayToString(string[] array)
{
StringBuilder buildingstring = new StringBuilder();
foreach (string value in array)
{
buildingstring.Append(value);
buildingstring.Append("\r\n");
}
return buildingstring.ToString();
}
I have gone around a different way, by creating a string array adding each value to the string array and using a separate function to join all of the string array data together and separating each value with a return
I have a tab delimited file, and some of the strings contain a ý character which needs to be replaced with a \t. Also, the string needs to contain 4 tabs total, with any extra tabs tacked on to the end. For example, the strings:
1234ý5678
1234
ý1234ý5678
should look like
1234\t5678\t\t\t
1234\t\t\t\t
\t1234\t5678\t\t
Here's what I have so far:
string[] input_file = (string[])(e.Data.GetData(DataFormats.FileDrop));
string output_file = #"c:\filename.txt";
foreach (string file in input_file)
{
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
string[] values = line.Split('\t');
//look at each value in values, replace any ý with a tab, and add
//tabs at the end of the value so there are 4 total
lines[i] = String.Join("\t", values);
}
File.WriteAllLines(output_file, lines);
}
EDIT: some clarification - the entire line might look like this:
331766*ALL1 16ý7 14561ý8038 14560ý8037 ausername 11:54:05 12 Nov 2007
I need to look at each string that makes up the line, and replace any ý with a \t, and add \t's to the end so each string has a total of 4. Here's what the result should look like:
331766*ALL1 16\t7\t\t\t 14561\t8038\t\t\t 14560\t8037\t\t\t ausername 11:54:05 12 Nov 2007
What you do is:
Split each line to strings using \t as separator.
Iterate through the strings.
For each string replace ý with \t.
Count the number of \t in the string now, and add additional \t as needed.
Here's some code:
string[] lines = System.IO.File.ReadAllLines(input_file);
var result = new List<string>();
foreach(var line in lines)
{
var strings = line.Split('\t');
var newLine = "";
foreach(var s in strings)
{
var newString = s.Replace('ý','\t');
var count = newString.Count(f=>f=='\t');
if (count<4)
for(int i=0; i<4-count; i++)
newString += "\t";
newLine += newString + "\t";
}
result.Add(newLine);
}
File.WriteAllLines(output_file, result);
This could possibly be optimized better for speed using StringBuilder, but it's a good start.
Try this:
string[] lines = System.IO.File.ReadAllLines(input_file);
for (int i = 0; i < lines.Length; i++)
{
string line = lines[i];
line = line.Replace("ý", "\t");
int n = line.Split(new string[] { "\t" }, StringSplitOptions.None).Count()-1;
string[] temp = new string[4 - n ];
temp = temp.Select(input => "\t").ToArray();
line += string.Join(string.Empty, temp);
lines[i] = line;
}
System.IO.File.WriteAllLines(output_file, lines);
private static string SplitAndPadded(string line, string joinedWith = "\t", char splitOn = 'ý')
{
// 4 required splits yields 5 items ( 1 | 2 | 3 | 4 | 5 )
// could/should be a parameter; this allowed for the cleaner comment
const int requiredItems = 5;
// the empty string case
var required = Enumerable.Repeat(string.Empty, requiredItems);
// keep empty items; 3rd test case
var parts = line.Split(new[] { splitOn });
// this will exclude items when parts.Count() > requiredItems
return string.Join(joinedWith, parts.Concat(required).Take(requiredItems));
}
//usage
// .Select(SplitAndPadded) may need to be .Select(line => SplitAndPadded(line))
var lines = File.ReadAllLines(file).Select(SplitAndPadded).ToArray();
File.WriteAllLines(outputFile, lines);
// if input and output files are different, you don't need the ToArray (you can stream)