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

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);

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);

Converting Character to Ascii

I've been creating a code breaking software and I need to convert the characters from a text file into ascii numbers to allow the shift. I have left my code below but could someone explain how I could do this?
using System;
using System.IO;
namespace CipherDecoder
{
class Program
{
static void Main(string[] args)
{
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
string cipherText = File.ReadAllText(fileText);
string output = #"C:\\Users\Samuel\Documents\Computer_Science\PaDS\output.txt\";
char[] cipherChars = new char[691];
int j = 0;
foreach (char s in cipherText)
{
cipherChars[j] = s;
j++;
}
for(int i = 0; i < cipherChars.Length; i++)
{
cipherChars[i] = cipherChars[i];
}
}
}
}
To get the int values into an int array you could just do this with as a LINQ select. For example:
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();
You can,
var asciiNumbersArray = cipherText.Cast<int>().ToArray();
If you cast a char to int you get the ascii number in decimal system.

Algorithm to find the three longest unique palindromes in a string

Using C#, write an algorithm to find the three longest unique palindromes in a string. For the three longest palindromes, report the palindrome text, start index and length in descending order of length. For example, the output for string,
sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop
should be:
Text: hijkllkjih, Index: 23, Length: 10 Text: defggfed, Index: 13, Length: 8 Text: abccba, Index: 5 Length: 6
Now I got to the part where I can write out the palindromes and its length but I have a problem with the index. Need help on how to include the index of the palindrome and how to get unique lengths
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string inputString = "sqrrqabccbatudefggfedvwhijkllkjihxymnnmzpop";
string currentStr = string.Empty;
List<string> listOfPalindromes = new List<string>();
char[] inputStrArr = inputString.ToCharArray();
for (int i = 0; i < inputStrArr.Length; i++)
{
for (int j = i+1; j < inputStrArr.Length; j++)
{
currentStr = inputString.Substring(i, j - i + 1);
if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(currentStr);
}
}
}
var longest = (from str in listOfPalindromes
orderby str.Length descending
select str).Take(3);
foreach (var item in longest)
{
Console.WriteLine("Text: " + item.ToString() + " Index: " + + " Length: " + item.Length.ToString());
}
}
private static bool IsPalindrome(String str)
{
bool IsPalindrome = true;
if (str.Length > 0)
{
for (int i = 0; i < str.Length / 2; i++)
{
if (str.Substring(i, 1) != str.Substring(str.Length - (i + 1), 1))
{
IsPalindrome = false;
}
}
}
else
{
IsPalindrome = false;
}
return IsPalindrome;
}
}
}
ok now that's out of the way how do I get distinct lengths? can it be done by using DISTINCT or do I need to edit something else?
You need to store more information when a palindrome is found.
First define a class:
class PalindromeResult
{
public string Text { get; set; }
public int Index { get; set; }
}
Then instead of your List<string>, create a list of this class:
List<PalindromeResult> listOfPalindromes = new List<PalindromeResult>();
When a result is found, ad it like this
if (IsPalindrome(currentStr))
{
listOfPalindromes.Add(new PalindromeResult { Text = currentStr, Index = i});
}
You would have to update your sorting and printing accordingly.
The most optimal solution (as pointed out by Sinatr) would be to store the index of the palindromes as you find them.
You could instead use the IndexOf function to find the index of the first occurrence of a substring within a string.
For example inputString.IndexOf(item) could be used in your Console.WriteLine function.
Try This
public static bool IsPalindromic(int l)
{
IEnumerable<char> forwards = l.ToString().ToCharArray();
return forwards.SequenceEqual(forwards.Reverse());
}
public int LongestPalindrome(List<int> integers)
{
int length=0;
int num;
foreach (var integer in integers)
{
if (integer.ToString().Length > length)
{
num = integer;
length = integer.ToString().Length;
}
}
return num;
}
public void MyFunction(string input)
{
var numbers = Regex.Split(input, #"\D+").ToList();
var allPalindromes = (from value in numbers where !string.IsNullOrEmpty(value) select int.Parse(value) into i where IsPalindromic(i) select i).ToList();
if (allPalindromes.Count>0)
Console.WriteLine(LongestPalindrome(allPalindromes));
else
Console.WriteLine("Any Palindrome number was found");
}
you cans mix the 2 two functions to have a beautiful code but i done it like this to simplify.

Reverse a char array in 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]);
}

Categories

Resources