Reverse a char array in C# - c#

I am trying to learn C#. I want to enter some text and for it to come out reversed. It reverses it, but multiple times, as many times as the inputted text is long. So hello comes out as olleholleholleholleholleh.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Reversed_Array
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text to be reversed");
string inputText = Console.ReadLine();
char[] myChar = inputText.ToCharArray();
Array.Reverse(myChar);
foreach (char character in myChar)
{
Console.Write(myChar);
}
Console.ReadLine();
}
}
}
I wanted to experiment with converting a string into a char array. Thought I would note this because yes I don't need the char array.

Because every time you write the whole array not a single character, try this:
foreach (char character in myChar)
{
Console.Write(character);
}

for( int i = myChar.Length -1 ; i >= 0 ; --i )
{
Console.Write(myChar[i]);
}

There's no need to have a special array, do a reverse etc., just print out characters backward:
static void Main(string[] args)
{
Console.WriteLine("Enter text to be reversed");
string inputText = Console.ReadLine();
// Backward loop
for (int i = inputText.Length - 1; i >= 0; --i)
Console.Write(inputText[i]);
}

Related

How can i enter from keyboard a phrase using an array?

here's what i understand it would be necessary to do:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public const int N = 100;
static void Main(string[] args)
{
char[] phrase = new char[N];
int i=0;
Console.WriteLine("enter a phrase: ");
while ((i < N) && (phrase[i] != '.'))
{
phrase[i] = Convert.ToChar(Console.ReadLine());
i++;
}
while(i<N){
Console.WriteLine(+phrase[i]+" ");
i++;
}
Console.ReadLine();
}
}
}
and also I want to know if there's a way I can enter a phrase without having to press intro for every character I introduce
Unless I'm missing something you can just do this:
static void Main(string[] args)
{
Console.WriteLine("enter a phrase: ");
string phrase = Console.ReadLine();
var chars = phrase.ToCharArray(); //If you want it as a char array
}
The Console.ReadLine() will read the line until the user hits return/enter and we can store this is the string phrase. If you do want the input in a char array you can use the .ToCharArray() function on the string

Getting and removing a part of a string by first and last occurance of character

I have a string like this:
{something:something}Some data will be here
Heres how its setup:
{username:password}data
How can I get the {username:password} part and remove it from the full string? I need to check the username and password then send the data (everything after {something:something}) to the user.
Preferably I would like to get the username:password without the {} so I can just split by :
Here is a regex solution :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string input = "{something:something}Some data will be here";
string pattern = #"\{(?'username'[^:]+):(?'password'[^\}]+)\}(?'data'.*)";
Match match = Regex.Match(input,pattern);
Console.WriteLine("Username : '{0}', Password : '{1}', Data : '{2}'",
match.Groups["username"].Value, match.Groups["password"].Value, match.Groups["data"].Value);
Console.ReadLine();
}
}
}
You can first use substring and index of to remove the unwanted characters.
string input = {username:password}data
input = input.Substring(input.IndexOf("}") +1); //data
This will give you the data part assuming } occurs only once.
public int IndexOfNth(string str, string value, int nth)
{
int offset = str.IndexOf(value);
for (int i = 0; i < nth; i++)
{
if (offset == -1) return -1;
offset = str.IndexOf(value, offset + 1);
}
return offset;
}
this method returns the index of the value you want to find ex)# fron the str and of the nth position ex)2 will return the 3rd occurance of # in chris#so#sk#
this can be used to substring Strings
maybe this will work:
string x= "{username:password}data";
string username = x.substring(1,IndexoOfNth(x,":",0)-1);

Removing extra letter sets in an inconsistent text file using Regex

I have a hard time figuring out how to remove extra letters using Regex.
I have this example below that says that it has 42 of "|" (vertical bars) per line.
|V.7|42|
1|0|1|58|4|4|351|25|8|||1|0||6|3|1000|49|20|430|17|6|0|10|0|1200|25||30|20|20|20|20|0|100|61028|1|0|0|1|1|0|
1|0|1|58|4|4|351|25|8|||1|0||6|3|1000|49|20|430|17|6|0|10|0|1200|25||30|20|20|20|20|0|100|61028|1|0|0|1|1|0|
2|543|2|58|4|4|366|26|9|100||2|200||8|3|1000|49|20|430|17|6|10|21|54|2400|36||30|20|20|20|20|543|150|61028|2|100|1|2|2|0|
3|1230|3|60|5|5|390|26|10|100||3|1500||10|3|1000|49|20|430|17|6|10|32|123|4800|46||30|20|20|20|20|1230|200|61028|3|1000|2|3|3|0|
4|2002|4|61|6|6|424|27|12|100||4|6000||12|4|769|37|15|315|12|4|10|45|200|9600|57||30|20|20|20|20|2002|250|61028|4|5000|3|4|4|0|
5|3306|5|63|7|7|468|29|14|100||5|18000||16|4|556|27|11|208|8|2|10|58|331||69||30|20|20|20|20|3306|300|61027|1|10000|4|5|5|0|
6|4950|6|66|8|8|522|31|17|100||6|||18|4|435|21|9|147|6|1|10|74|495||80||30|20|20|20|20|4950|350|61027|2|30000|5|6|6|0|
7|6947|7|69|10|10|585|33|20|100||7|||20|4|333|17|7|97|4|1|10|90|695||92||20|15|15|15|15|6947|400|61027|3|50000|6|7|7|0|
8|9309|8|73|12|12|658|35|24|100||8|||24|4|286|14|6|73|3|1|10|109|931||105||20|15|15|15|15|9309|450|61026|1|100000|7|8|8|0|
9|12050|9|77|14|14|741|38|28|100||9|||27|5|250|13|5|55|3|1|10|129|1205||117||20|15|15|15|15|12050|500|61026|2|300000|8|9|9|0|
10|15183|10|82|16|16|834|41|33|100|100|10|||29|5|222|11|4|0|0|0|10|151|1366||130|5|20|15|15|15|15|15183|550|61025|1|500000|9|10|10|0|
11|18720|11|87|19|19|936|45|38|100|100|11|||31|5|200|10|4|0|0|0|11|176|1685||143|10|20|15|15|15|15|18720|600|||||||0|
12|21335|12|92|22|22|1048|48|44|100|100|12|||36|5|182|9|4|0|0|0|12|203|2134||157|15|10|15|10|10|10|21335|650|||||||0|
Now I have another one with 45, what I want is to remove the new letters so that it has exactly 42 vertical bars like above.
|V.8|45|
1|0|1|58|4|4|351|25|8|||1|0||6|3|1000|49|20|430|17|6|0|10|0|1200|25||30|20|20|20|20|0|100|61028|1|0|0|1|1|0|5000|40022|1|
2|543|2|58|4|4|366|26|9|100||2|200||8|3|1000|49|20|430|17|6|10|21|54|2400|36||30|20|20|20|20|543|150|61028|2|100|1|2|2|0|25000|61034|1|
3|1230|3|60|5|5|390|26|10|100||3|1500||10|3|1000|49|20|430|17|6|10|32|123|4800|46||30|20|20|20|20|1230|200|61028|3|1000|2|3|3|0|75000|40250|1|
4|2002|4|61|6|6|424|27|12|100||4|6000||12|4|769|37|15|315|12|4|10|45|200|9600|57||30|20|20|20|20|2002|250|61028|4|5000|3|4|4|0|160000|61035|1|
5|3306|5|63|7|7|468|29|14|100||5|18000||16|4|556|27|11|208|8|2|10|58|331||69||30|20|20|20|20|3306|300|61027|1|10000|4|5|5|0|300000|40355|3|
6|4950|6|66|8|8|522|31|17|100||6|||18|4|435|21|9|147|6|1|10|74|495||80||30|20|20|20|20|4950|350|61027|2|30000|5|6|6|0||||
7|6947|7|69|10|10|585|33|20|100||7|||20|4|333|17|7|97|4|1|10|90|695||92||20|15|15|15|15|6947|400|61027|3|50000|6|7|7|0||||
8|9309|8|73|12|12|658|35|24|100||8|||24|4|286|14|6|73|3|1|10|109|931||105||20|15|15|15|15|9309|450|61026|1|100000|7|8|8|0||||
9|12050|9|77|14|14|741|38|28|100||9|||27|5|250|13|5|55|3|1|10|129|1205||117||20|15|15|15|15|12050|500|61026|2|300000|8|9|9|0||||
10|15183|10|82|16|16|834|41|33|100|100|10|||29|5|222|11|4|0|0|0|10|151|1366||130|5|20|15|15|15|15|15183|550|61025|1|500000|9|10|10|0||||
11|18720|11|87|19|19|936|45|38|100|100|11|||31|5|200|10|4|0|0|0|11|176|1685||143|10|20|15|15|15|15|18720|600|||||||0||||
12|21335|12|92|22|22|1048|48|44|100|100|12|||36|5|182|9|4|0|0|0|12|203|2134||157|15|10|15|10|10|10|21335|650|||||||0||||
And I have this code at the moment:
public string Fix(string FileName, int columnsCount)
{
var InputFile = File.ReadLines(FileName).Skip(1).ToArray();
string Result = "";
for(int i = 0; i < InputFile.Length; i++)
{
int FoundMatches = Regex.Matches(Regex.Escape(InputFile[i]), FindWhatTxtBox.Text).Count;
// If too many letters found, trim the rest.
if(FoundMatches > CountTxtBox.Text.Length)
{
string CurrentLine = InputFile[i];
}
}
return Result;
}
As you can see each line has either one to no numbers inside its vertical bar. How can I remove the extra letters?
Do you have to use a RegEx? It can also be done with string manipulation like this:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string s = "1|0|1|58|4|4|351|25|8|||1|0||6|3|1000|49|20|430|17|6|0|10|0|1200|25||30|20|20|20|20|0|100|61028|1|0|0|1|1|0|5000|40022|1|";
var arr = s.Split('|') ;
var retVal = String.Join("|", arr.Take(43));
Console.WriteLine(retVal);
}
}
It takes 43 because the 1st digit seems a counter to me... But you can make it 42 of course. Beware that this code will fail is there are less than 43 entries to work with.
Too simple to use Regex. See code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string INPUT_FILENAME = #"c:\temp\test.txt";
const string OUTPUT_FILENAME = #"c:\temp\test1.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(INPUT_FILENAME);
StreamWriter writer = new StreamWriter(OUTPUT_FILENAME);
string inputLine = "";
int lineCount = 0;
while ((inputLine = reader.ReadLine()) != null)
{
if (++lineCount == 1)
{
writer.WriteLine(inputLine);
}
else
{
string[] inputArray = inputLine.Split(new char[] {'|'});
writer.WriteLine(string.Join("|", inputArray.Take(43)));
}
}
reader.Close();
writer.Flush();
writer.Close();
}
}
}
Here is a data file, let us keep it easy by only needing 5 items but still using Regex.
Keep your examples small for StackOverflow...one will get more answers.
The below code can be changed to 42 ({0,42}) or any number as needed, but the example will read then write out only 5.
Data File
1|2|3|4|5|6|7|8|9|10
10|9|8|7|6|5|4|3|2|1|0|1|
||||||||||||11|12|
Code To get 0 to 5 Items per line
var data = File.ReadAllText(#"C:\Temp\test.txt");
string pattern = #"^(\d*\|){0,5}";
File.WriteAllLines(#"C:\Temp\testOut.txt",
Regex.Matches(data, pattern, RegexOptions.Multiline)
.OfType<Match>()
.Select(mt => mt.Groups[0].Value));
Resultant File
1|2|3|4|5|
10|9|8|7|6|
|||||

C# setting length of main string as length of a substring

I have problem with the .length code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static void Main(string[] args)
{
string Str_Basics = "AIKdepNCZSIDETe";
int Long_Str_Bas;
string Sub_Str_1;
string Sub_Str_2;
Long_Str_Bas = Str_Basics.Length;
//Provide value for M
int M = 0;
Console.WriteLine("Provide value for M");
M = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < Long_Str_Bas; i++) ;
// First substring
Sub_Str_1 = Str_Basics.Substring(1, (M - 1));
// Second substring
Sub_Str_2 = Str_Basics.Substring((M + 1),Long_Str_Bas);
Console.WriteLine("Substring is " + Sub_Str_1);
Console.WriteLine("Substring is " + Sub_Str_2);
Console.ReadKey();
}
}
I do not know how to transfer Str_Basics.Length into a cordinates of Sub_Str_2 if anyone could explain me how does the .Length works I would be really thankful.
It sounds like you just want to do this:
// First substring
Sub_Str_1 = Str_Basics.Substring(0, M);
// Second substring
Sub_Str_2 = Str_Basics.Substring(M);

Find all the words containing more than 10 letters in string from text file

Down below I have written code that successfully checks if the text file I enter has the character "A" in it. It returns yes or no based on the result. However, now I would like to list all the words bigger than 10 characters. Please note that I use ReadAllText when I read the string. Therefore the whole text file is within the same string. I'm looking for the way to think rather than oven-ready code. Thank you all!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TESTING
{
class Testing
{
static void Main(string[] args)
{
//ask user for the filename
string userInput = fetchFileName("Enter the textfile you want to view: ");
//test if the filename writes anything to console
string fileContents = File.ReadAllText(userInput);
string theFileContents = analyseFile(fileContents);
//Console.WriteLine(theFileContents);
Console.ReadLine();
}
private static string analyseFile(string fileContents)
{
string str = fileContents;
if (str.Contains("A"))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
return str;
}
private static string fetchFileName(string askFileName)
{
Console.WriteLine(askFileName);
string userAnswer = Console.ReadLine();
return userAnswer;
}
}
}
Since your file is in a string, you could use string's Split method to convert it to tokens ("words"):
var tokens = fileContents.Split(' ', '\t', '\n', '\r');
With an array of tokens in hand, use the filtering technique that you prefer to keep only 10-character words. C# offers many choices to do that - you could use a for loop, a foreach loop, or use Where extension method provided by LINQ.
just split your fileContent in words using String.Split(' ') and check then make a LINQ-query on the resulting array returning every word with Length > 10.
Sth. like this:
string fileContents = File.ReadAllText(userInput);
var result = fileContents.Split(' ').Where(x => x.Length > 10);
This should work but is not tested
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace test1
{
class Program
{
static void Main(string[] args)
{
//ask user for the filename
string userInput = fetchFileName("Enter the textfile you want to view: ");
//test if the filename writes anything to console
string fileContents = File.ReadAllText(userInput);
string theFileContents = analyseFile(fileContents);
// Console.WriteLine(theFileContents);
foreach (var item in tenOrMore(fileContents))
{
Console.WriteLine(item);
}
Console.ReadLine();
}
private static IEnumerable<string> tenOrMore(string fileContents)
{
foreach (var item in fileContents.Split(' ', '\t', '\n', '\r'))
{
if (item.Length.CompareTo(10) > 0)
{
yield return item;
}
}
}
private static string analyseFile(string fileContents)
{
string str = fileContents;
if (str.Contains("A"))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
return str;
}
private static string fetchFileName(string askFileName)
{
Console.WriteLine(askFileName);
string userAnswer = Console.ReadLine();
return userAnswer;
}
}
}
use Split as below:
ArrayList ar=new ArrayList(); // list of strings with the lenghth of greater than 10
String[] userInputWords=userInput.Split(' ', '\t', '\n', '\r');
foreach(String str in userInputWords){
if (str.Length()>10){
ar.add(str);
}
}
Another, more naive way is to start from the beginning of the string and increment letter counter every time you encounter anything that isn't a whitespace character.
When you do encounter a whitespace, see if the letter counter is > 10. If yes, the word was longer than 10 characters. Reset letter counter to 0 and continue searching for words until the end of file.
This approach has an advantage of not doing splitting and extra string allocation, which is may be a lot of work for large files with many words.
Pseudocode:
letterCount = 0
wordCount = 0
letter = GetNextLetter()
while (isNotEndOfFile())
{
if (notAWhitespace(letter))
{
letterCount++
}
else
{
if (letterCount > 10) { wordCount++ }
letterCount=0
}
letter = GetNextLetter()
}
if (letterCount > 10) { wordCount++ }

Categories

Resources