I'm need generate a random number an insert a space or comma between digits. This value will be speaked using AWS Polly. Without space, to 6565, she sepeak "six thousand five hundred and sixty five".
Part of the code, generating the random number, I already got it, but I don't know how to insert the space between the digits.
Anyone can help me? See bellow:
var withoutSpaces = new Random().Next(10000,100000);
var withSpaces = ????????
return withSpaces;
Wait your answer!
var withoutSpaces = new Random().Next(10000, 100000);
string withSpaces = "";
for (int i = 0; i < withoutSpaces.ToString().Length; i++)
{
string test = withoutSpaces.ToString().ElementAt(i) + " ";
withSpaces += test;
}
string WithSpacesFinal = withSpaces.Trim();
This should do it for you
Related
I have huge string e.g (This is just the part, the string looks same it has just a bit different values).
string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";
So I have to swap the whole number e.g.
Output should be:
9.16364437205161 48.7465504247904
Also I need to swap the first and second part.
So I've tried to split the string, and then to replace the old one with the new one.
string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";
string output = "";
double first = 0;
double second = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers.Split(' ');
first = numbers[0];
second = numbers[1];
}
output = numbers.Replace(numbers[1], numbers[0]);
Console.WriteLine(output);
But my variable first always after the loop has the value 52.
Right now my output is: 44.7465504247904 9.16364437205161, it changed the first part, also it calculates somehow -4
.
You're not assigning anything to the value coming back from .Split and, if I read this right, you're also iterating each character in the numbers array for unclear reasons.
Using .Split is all you need ... well, and System.Linq
using System.Linq;
// ...
string SwapNumbers(string numbers) {
return numbers.Split(' ').Reverse().Join();
}
The above assumes you want to reverse the whole series of numbers. It absolutely does not swap 1,2 then swap 3,4 etc. If that's what you're looking for, it's a bit more involved and I'll add that in a second for funsies.
string SwapAlternateNumbers(string numbersInput) {
var wholeSeries = numbersInput.Split(' ').ToList();
// odd number of inputs
if (wholeSeries.Count % 2 != 0) {
throw new InvalidOperationException("I'm not handling this use case for you.");
}
var result = new StringBuilder();
for(var i = 0; i < wholeSeries.Count - 1; i += 2) {
// append the _second_ number
result.Append(wholeSeries[i+1]).Append(" ");
// append the _first_ number
result.Append(wholeSeries[i]).Append(" ");
}
// assuming you want the whole thing as a string
return result.ToString();
}
Edit: converted back to input and output string. Sorry about the enumerables; that's a difficult habit to break.
here
public static void Main()
{
string nums = "48.7465504247904 9.16364437205161 48.7465504247904 9.16364437205161";
var numbers = nums.Split(' ');
var swapped = numbers.Reverse();
Console.WriteLine("Hello World {"+string.Join(" ",swapped.ToArray())+"}");
}
I am trying to code a simple game where my program randomly selects a word from a dictionary and stores it in a text box/or label? (Not Sure of this part). Then I have another text box where the user enters his guess.
Now I want to give the user some hint.F or example the word:
'game' would look like '_ a m _' or 'g _ _ e'. I have no preference to how the characters are placed.
I have programmed all of the previous code including the random file handling method, all timers and counter etc. I am just stuck on this part.
The program undergoes the following code :
var lines = File.ReadAllLines(#"LOCATION");
textBox3.Text = lines[new Random().Next(lines.Length)];
to select a random word from the file. However the whole word is being shown in textbox 3 and not parts of it like i wish. I am at a complete loss for ideas on how to proceed. I could not find anything similar on the web.
Cheers,
R
Once you pick a random word from file, based on length of the word, decide on how many characters you'd want to hide and then randomly replace those many characters.
something like this-
public string GetPartialWord(string word)
{
if(string.IsNullOrEmpty(word))
{
return string.Empty;
}
char[] partialWord = word.ToCharArray();
int numberOfCharsToHide = word.Length / 2;
Random randomNumberGenerator = new Random();
HashSet<int> maskedIndices = new HashSet<int>();
for(int i=0;i<numberOfCharsToHide;i++)
{
int rIndex = randomNumberGenerator.Next(0, word.Length);
while(!maskedIndices.Add(rIndex))
{
rIndex = randomNumberGenerator.Next(0, word.Length);
}
partialWord[rIndex] = '_';
}
return new string(partialWord);
}
The code below will replace at least half of the characters with underscores. The code takes a word and keeps generating random numbers until it has replaced at least half of the characters with underscores.
public string ConvertToGuessWord(string word)
{
var guessWord = word;
int lastRandom = 0;
do
{
Random rand = new Random();
int thisRandom = 0;
do
{
thisRandom = rand.Next(0, guessWord.Length);
} while (lastRandom == thisRandom);
guessWord = guessWord.Replace(guessWord[thisRandom], '_');
lastRandom = thisRandom;
} while (guessWord.Count(x => x == '_') < (word.Length / 2));
return guessWord;
}
I'm trying to add spaces between characters in a string in c#... Any advice would be very much appreciated.. Thanks
using System;
namespace nameReverser
{
class Program{
public static void Main(string[] args )
{ Console.WriteLine("Magical Name Reverser");
//User enters name
Console.WriteLine("Please Enter Your Name:");
string name = Console.ReadLine();
char[] cArray = name.ToCharArray();
string nameReversed = String.Empty;
for (int i= cArray.Length - 1; i>-1; i--)
{
nameReversed +=cArray[i];
}
Console.WriteLine("Your name in reverse order is:");
Console.WriteLine(nameReversed);
}
}
}
You can use String.Join to get a new string from array having a single space as separator. To print it in reverse order you can use Array.Reverse() hence your whole code will be like the following:
Console.WriteLine("Magical Name Reverser");
Console.WriteLine("Please Enter Your Name:");
string name = Console.ReadLine();
char[] cArray = name.ToCharArray();
Array.Reverse(cArray);
string resultString = String.Join(" ", cArray);
Console.WriteLine(resultString );
Console.WriteLine("Your name in reverse order is:");
Can be done in one-go
strResult= String.Join(" ", name.Reverse());
In addition to un-lucky's answer which adds spaces after each letter you can as well use the Insert() method of a string to add a space at a certain index
Example:
name = "Rudolf";
name.Insert (1, " ");
results to "R udolf"
Something like this
strResult= yourString(" ", name.Reverse());
Normally, I would recommend one of the other answers, if you only want to insert spaces into the string.
But in your example code, since you are looping through the string anyway, you can combine the reversal operation with the space insertion operation:
// ....
for (int i = cArray.Length - 1; i > -1; i--)
{
nameReversed += cArray[i] + " ";
}
// ...
Better yet, as suggested in the comments: if you are going to add to a string repeatedly, consider using a StringBuilder:
StringBuilder reverseBuilder;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverseBuilder.Append(cArray[i]);
reverseBuilder.Append(' ');
}
// ...
nameReversed = reverseBuilder.ToString();
Slightly off subject...
If you want to add spaces between characters in a fixed width number like a time, you can also use the string format syntax:
int time = 1204; //represents 12:04
int hh = time / 100;
int mm = time - hh * 100;
string result = string.Format("{0:0 0} : {1:0 0}", hh, mm);
//result is 1 2 : 0 4
I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"
I'm rubbish at explaining things so I'm just going to let the code do the talking. This is a section of code I have
PIDages.Sort();
lollist.WriteLine();
foreach (int a in PIDages)
{
lollist.Write(a + " ");
}
PIDages.Clear();
This code is repeated many times. At the moment it will output the each list on a new line in the following format
13*SPACE*
13 13*SPACE*
1 2 8*SPACE*
Is there an easy fix to not have the space character at the end of every line?
you can use the string.Join function
lollist.WriteLine(String.Join(" ", PIDages));
I'm currently not sure if a cast is necessary, in C# 2.0 the syntax would be
lollist.WriteLine(String.Join(" ", PIDages.Select(a => a.ToString()).ToArray());
You could first concatenate the string and then use Trim to get rid of any spaces at the start or the end of the string.
A little bit like that:
string result = String.Empty;
foreach (int a in PIDages)
{
result = result + a + " ";
}
result = result.Trim();
lollist.Write(result);
If you want to skip space at the end of string
You can try :
PIDages.Sort();
lollist.WriteLine();
string sResult = string.Empty;
foreach (int a in PIDages)
{
sResult += (a + " ");
}
lollist.Write(sResult.Trim());
PIDages.Clear();
Keep it simple?
bool add_space = false;
PIDages.Sort();
lollist.WriteLine();
foreach (int a in PIDages)
{
if (add_space)
lollist.Write(" ");
else
add_space = true;
lollist.Write(a);
}
PIDages.Clear();