I just get System.IndexOutOfRangeException [duplicate] - c#

This question already has answers here:
Reverse word of full sentence
(20 answers)
Closed 2 years ago.
I've been tried to do an algorithm that ask for a sentence and put the words backwards, for example if I insert "Cookies and milk" it would give back "milk and Cookies", but it gives me System.IndexOutOfRangeException in the second for. Please help
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string sentence;
string spac = " ";
char[] phr;
char space = char.Parse(spac);
Console.WriteLine("Write a sentence");
sentence = Console.ReadLine();
phr = sentence.ToCharArray();
for (int i = phr.Length-1; i >= 0; i--)
{
if (phr[i] == space)
{
for (int j = i++; phr[j] != phr.Length-1 || phr[j]!=space; j++)
{
Console.WriteLine(phr[j]);
}
}
}
}
}
}

You can split a string into an array based on any character. If you split by space you can keep the words intact. Do this, then reverse the order, and join it again.
string sentence = "Cookies and Milk";
string wordsReversed =
string.Join(" ",
sentence.Split(' ').Reverse()
);
Console.WriteLine(wordsReversed); // "Milk and Cookies"

Related

Is there a way to properly case names after user inputs their names in C#? [duplicate]

This question already has answers here:
Converting string to title case
(23 answers)
Closed 11 months ago.
I am trying to figure out how to sort input names to right capitalization eg: tim jAmes = Tim James
I have sorted it up to where i can take in the name, but the sorting out has been doing my head in, not very familiar with c# yet but i need this for a test i am doing .
Here's my exisiting code:
Console.WriteLine("What is your name?");
var str = Console.ReadLine();
Console.WriteLine("Hello there, " + str);
This is a simple approach:
Console.WriteLine("What is your name?");
var str = Console.ReadLine();
TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
str = textInfo.ToTitleCase(str);
Console.WriteLine("Hello there, " + str); //Hello there, Tim James
Just make sure that you include: using System.Globalization; at the top
This cannot be done reliably because there are just many different kind of names that don't follow the basic rule with the first letter being capital followed by lowercase letters. One example is Neil deGrasse Tyson.
You may try ToTitleCase as others suggested - and this even covers , but if you doing this as an exercise to learn programming you could go back to basics and try with Split and ToLower and ToUpper:
using System.Globalization;
var name = "tim jAmes";
Console.WriteLine($"{name} => {FixName(name)}");
string FixName(string name)
{
var culture = new CultureInfo(name: "en-US", useUserOverride: false);
if( name.ToLower() == "Neil deGrasse Tyson".ToLower())
{
return "Neil deGrasse Tyson"; // ;)
}
var parts = name.Split(" ");
var fixedParts = new List<string>();
foreach(var part in parts)
{
var fixedPart = char.ToUpper(part[0], culture)
+ part.Substring(startIndex: 1).ToLower(culture);
fixedParts.Add(fixedPart);
}
var fixedName = string.Join(" ", fixedParts);
return fixedName;
}
This prints:
tim jAmes => Tim James
You can roll your own by using static methods of the char class.
The idea is to only capitalize characters that are preceded by a non letter character. This is a naive way of approaching this, but fun to tinker around with.
var input = "TIM JAMES";
var output = "";
var thisChar = ' ';
var shouldCapitalize = true;
for (int i = 0; i < input.Length; i++)
{
thisChar = input[i];
if (!char.IsLetter(thisChar))
{
shouldCapitalize = true;
}
else
{
if (shouldCapitalize)
{
thisChar = char.ToUpper(thisChar);
shouldCapitalize = false;
}
else
{
thisChar = char.ToLower(thisChar);
}
}
output += thisChar;
}
Console.WriteLine("Hello there, " + output);
To handle Mc names, eg. McDonuts, you can do the following.
private bool IsMcName(string output, int index, char currentChar)
{
return
index > 0 &&
char.ToLower(currentChar) == 'c' &&
output[index - 1] == 'M';
}
and call this function from the else statement where the current char is converted to lower case.
else
{
if (IsMcName(output, i, thisChar))
{
shouldCapitalize = true;
}
thisChar = char.ToLower(thisChar);
}
I made a similar function for Mac names, eg MacDonuts, and it works.. however I believe it would interfere more times than help. eg. Macy becomes MacY.
private bool IsMacName(string output, int index, char currentChar)
{
return
index > 1 &&
char.ToLower(currentChar) == 'c' &&
output[index - 1] == 'a' &&
output[index - 2] == 'M';
}
This can be used in-place, or in-conjunction with, the McName function. eg. if (McName(..) || MacName(..))

How to swap first and last letters in each word?

I have a practice session on C#, and I want to know how can I swap first and last characters in each word of a sentence and lower case them. I have created a string array that represents each word, and in an inner for loop, I am iterating each character in each word. There is my code.
using System;
namespace ConsoleApp11
{
class Program
{
static void Main(string[] args)
{
string text = "Hello world";
string[] words = text.Split(" ");
string output = "";
for(int i = 0; i < words.Length; i++)
{
for(int j = 0; j < words[i].Length; j++)
{
if (char.IsUpper(words[i][j]))
{
output += char.ToLower(words[i][j]);
}
else
{
output += words[i][j];
}
}
output += " ";
}
Console.WriteLine(output);
}
}
}
Because It is sunday :-), here is the complete code (my explanations were to difficult):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string output = "ABCD EFGH IJKL";
string[] outputs = output.Split(' ');
char[] chars;
string first,last;
string flower,llower;
string result = string.Empty;
for (int i = 0; i < outputs.Length; i++)
{
chars = outputs[i].ToCharArray();
first = new string(chars[0], 1);
last = new string(chars[chars.Length - 1], 1);
flower = first.ToLower();
llower = last.ToLower();
chars[chars.Length - 1] = flower.ToCharArray()[0];
chars[0] = llower.ToCharArray()[0];
result += new string(chars);
result += " ";
}
Console.WriteLine(output);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Result: dBCa hFGe lJKi
How do I lowercase and reverse the first and last characters in each word.
Solution using a regular expresion
We could use the Split() method of String or Regex, to split on non-word characters, but then we wouldn't be able to output the correct characters between each word, unless we only split on a single character.
using System;
using System.Text.RegularExpressions;
namespace CS_Regex {
class Program {
static void Main(string[] args) {
// Match words using a regular experession
string match_word = #"(\w+)";
string match_non_word = #"([^\w]*)";
string pattern = match_non_word + match_word + match_non_word;
Regex rx = new Regex(pattern, RegexOptions.Compiled);
// Do the match on example data
string data = "Hello world";
MatchCollection matches = rx.Matches(data);
// Output the matches
foreach (Match match in matches) {
// Get the text before and after the word
string non_word_before = match.Groups[1].ToString();
string non_word_after = match.Groups[3].ToString();
// Get the matched word
string word = match.Groups[2].ToString();
// Lower case the first and last characters and swap them
string firstchar = (word.Length > 0) ? $"{char.ToLower(word[0])}" : "";
string lastchar = (word.Length > 1) ? $"{char.ToLower(word[word.Length - 1])}" : "";
string middle = (word.Length > 2) ? word.Substring(1, word.Length - 2) : "";
string newword = lastchar + middle + firstchar;
// Output the new word
Console.Write(non_word_before + newword + non_word_after);
}
} // Main
} // class
} // namespace
Output from the proposed solution
oellh dorlw
Links
Regular Expression Language - Quick Reference
Regex Class
Regex.Match Method
one idea is to convert each string into an array of chars then, for each array of caracters, get the first and last caracter and convert those caratcter into string (of one caracter) in order to use the lower function. Then replace the first and last letters with the lower caracters by inverting the 0 index with the last index, in order to swap.
Example for first letter (NO swap just for explaination):
string output = "ABCD";
char[] chars = output.ToCharArray();
string firt = new string(chars[0],1);
string lower = firt.ToLower();
string result = output.Replace(chars[0].ToString(), lower.ToString());
For the swap of the first letter to the last
Here is a complete code for first letter: result is "BCDa". For the last letter, it is the same idea
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string output = "ABCD";
char[] chars = output.ToCharArray();
string firt = new string(chars[0],1);
string lower = firt.ToLower();
chars[chars.Length-1] = lower.ToCharArray()[0];
string result = new string(chars);
Console.WriteLine(output);
Console.WriteLine(result);
Console.ReadLine();
}
}
}

How to make an string input from user into an array of the individual letters in the input? [duplicate]

This question already has answers here:
Split string into string array of single characters
(8 answers)
Closed 2 years ago.
I am making a solution where the user inputs a word or just letters and it shows the permutations of the word without duplicates. How could i make it so the input is made into an array of characters.(I am modifying another persons code to try and do this) so I want to assign a given value where i commented SOMEHOW in my code below so that I can Split it into the array. Im new to coding and would appreciate the help.
public static void Main()
{
string input;
//char word_inputed;
Console.WriteLine("Please print a word");
input = Console.ReadLine();
//string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = input.Split(' ');
foreach (var word in words)
{
foreach (var letter in word)
{
//SOMEHOW values = Console.Write($"{letter},");
}
}
ArrayList list = new ArrayList();
list.AddRange(values.Split(new char[] { ',' }));
char[] word_inputed = { 'A' };
int n = word_inputed.Length;
findPermutations(word_inputed, 0, n);
}
Here is the Microsoft sample
// Sample for String.ToCharArray(Int32, Int32)
using System;
class Sample {
public static void Main() {
string str = "012wxyz789";
char[] arr;
arr = str.ToCharArray(3, 4);
Console.Write("The letters in '{0}' are: '", str);
Console.Write(arr);
Console.WriteLine("'");
Console.WriteLine("Each letter in '{0}' is:", str);
foreach (char c in arr)
Console.WriteLine(c);
}
}
/*
This example produces the following results:
The letters in '012wxyz789' are: 'wxyz'
Each letter in '012wxyz789' is:
w
x
y
z
*/
door

How can i get the total occurrence of letter K? [duplicate]

This question already has answers here:
Number of occurrences of a character in a string [duplicate]
(6 answers)
Closed 6 years ago.
I want to check on how many times does k appears. this is
what i have done so far and am not getting the results.
class Program
{
static void Main(string[] args)
{
int count = 0;
string str = "hnfdjkkedjjykukyukrtrnrkkkkt";
string l;
for (int i = 0; i < str.Length; i++)
{
l = str.Substring(1, 1);
if (l == "k")
{
count++;
}
}
Console.WriteLine("k appears " + count++ + " times");
Console.ReadKey();
}
}
You can try :
int count = str.Count(c => c=='k')
Hope this help :-)
You can go as simple as
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string s = "aasfkkfasfas";
int count = s.Count(l => l== 'k');
Console.WriteLine(count);
}
}
Calling Substring for each letter is really not the best solution. Keep in mind that string implements IEnumerable so you can also do it like this:
using System;
public class Program
{
public static void Main()
{
string s = "aasfkkfasfas";
int count = 0;
foreach(char c in s)
{
if(c == 'k')
count++;
}
Console.WriteLine(count);
}
}
This is closer to your original solution.
You can also use RegEx (Regular Expressions) for that but it's kind of overkill for your use case.
It's found in the namespace System.Text.RegularExpressions (see MSDN).
Regex.Matches(text, pattern).Count
In your case, it would be
Regex.Matches("hnfdjkkedjjykukyukrtrnrkkkkt", "[k]").Count

How to remove spaces to make a combination of strings [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've been trying to figure out the best approach to combining words in a string to make combinations of that string. I'm trying to do this for a class project. If the string is "The quick fox", I need to find a way to output "Thequick fox", "the quickfox", and "thequickfox". I've tried using string.split and gluing them back together, but haven't had a lot of luck. The issues is the string input could be of any size.
I decided to try this for fun. The idea here is to split the bigger problems into smaller subproblems. So I first started with strings that had 0 and 1 space. I see that with 0 space, the only possible combinations is the string items. With 1 space, I can either have that space or not.
Then I just have to recursively divide the problem until I get one of the base cases. So to that do that I Skip elements in the split array in increments of 2. That way I am guaranteed to get one of the base cases eventually. Once I do that, I run it through the program again and figure out how to add all the results of that to my current set of combinations.
Here's the code:
class Program
{
static void Main(string[] args)
{
string test1 = "fox";
string test2 = "The quick";
string test3 = "The quick fox";
string test4 = "The quick fox says";
string test5 = "The quick fox says hello";
var splittest1 = test1.Split(' ');
var splittest2 = test2.Split(' ');
var splittest3 = test3.Split(' ');
var splittest4 = test4.Split(' ');
var splittest5 = test5.Split(' ');
var ans1 = getcombinations(splittest1);
var ans2 = getcombinations(splittest2);
var ans3 = getcombinations(splittest3);
var ans4 = getcombinations(splittest4);
var ans5 = getcombinations(splittest5);
}
static List<string> getcombinations(string[] splittest)
{
var combos = new List<string>();
var numspaces = splittest.Count() - 1;
if (numspaces == 1)
{
var addcombos = AddTwoStrings(splittest[0], splittest[1]);
var withSpacesCurrent = addcombos.Item1;
var noSpacesCurrent = addcombos.Item2;
combos.Add(withSpacesCurrent);
combos.Add(noSpacesCurrent);
}
else if (numspaces == 0)
{
combos.Add(splittest[0]);
}
else
{
var addcombos = AddTwoStrings(splittest[0], splittest[1]);
var withSpacesCurrent = addcombos.Item1;
var noSpacesCurrent = addcombos.Item2;
var futureCombos = getcombinations(splittest.Skip(2).ToArray());
foreach (var futureCombo in futureCombos)
{
var addFutureCombos = AddTwoStrings(withSpacesCurrent, futureCombo);
var addFutureCombosNoSpaces = AddTwoStrings(noSpacesCurrent, futureCombo);
var combo1 = addFutureCombos.Item1;
var combo2 = addFutureCombos.Item2;
var combo3 = addFutureCombosNoSpaces.Item1;
var combo4 = addFutureCombosNoSpaces.Item2;
combos.Add(combo1);
combos.Add(combo2);
combos.Add(combo3);
combos.Add(combo4);
}
}
return combos;
}
static Tuple<string, string> AddTwoStrings(string a, string b)
{
return Tuple.Create(a + " " + b, a + b);
}
}
}
This is how I got it working, not sure if it is the best algorithm.
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a string");
string input = Console.ReadLine();
//split the input string into an array
string[] arrInput = input.Split(' ');
Console.WriteLine("The combinations are...");
//output the original string
Console.WriteLine(input);
//this loop decide letter combination
for (int i = 2; i <= arrInput.Length; i++)
{
//this loop decide how many outputs we would get for a letter combination
//for ex. we would get 2 outputs in a 3 word string if we combine 2 words
for (int j = i-1; j < arrInput.Length; j++)
{
int end = j; // end index
int start = (end - i) + 1; //start index
string output = Combine(arrInput, start, end);
Console.WriteLine(output);
}
}
Console.ReadKey();
}
//combine array into a string with space except from start to end
public static string Combine(string[] arrInput, int start, int end) {
StringBuilder builder = new StringBuilder();
bool combine = false;
for (int i = 0; i < arrInput.Length; i++) {
//first word in the array... don't worry
if (i == 0) {
builder.Append(arrInput[i]);
continue;
}
//don't append " " if combine is true
combine = (i > start && i <= end) ? true : false;
if (!combine)
{
builder.Append(" ");
}
builder.Append(arrInput[i]);
}
return builder.ToString();
}
}

Categories