I want the user to first type a code (e.g. fkuk3463kj)
The array is limited to 20.
The rest must be filled with fillers.
Which filler the customer will use (e.g. #, t, z,7,_,0) is his own choice and he will asked to define it at the beginning right after the question for the code.
(hint: afterwards (or if possible directly) I have to decide (to complete the wish of customer) whether the filler has to be at the beginning or at the end.
(for example: fkuk3463kj########## or ##########fkuk3463kj)
Now I don't know how to implement this. I know, that it's not that difficult, but I don't get it! All my tryings were not really succesful.
Could anybody help me? This would be perfect!
And many thx in advance!
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
string[] CNr = new string[companyNr.Length];
Console.WriteLine("Type a filler");
string filler= Convert.ToString(Console.ReadLine());
string[] fill = new string[filler.Length];
.
.
.
.
.
(please pardon my english...)
As far as I can see, you're working with string:
// Trim: let's trim off leading and trailing spaces: " abc " -> "abc"
string companyNr = Console.ReadLine().Trim();
which you want to Pad with some char up to the length length (20 in your case):
int length = 20;
string filler = Console.ReadLine().Trim();
// padding character: either provided by user or default one (#)
char pad = string.IsNullOrEmpty(filler) ? '#' : filler[0];
// shall we pad left: "abc" -> "##abc" or right: "abc" -> "abc##"
// I have to decide (to complete the wish of customer)
//TODO: whether the filler has to be at the beginning or at the end
bool leftPad = true;
string result = leftPad
? companyNr.PadLeft(length, pad)
: companyNr.PadRight(length, pad);
// in case you want a char array
char[] array = result.ToCharArray();
// in case you want a string array
string[] strArray = result.Select(c => c.ToString()).ToArray();
Since you are getting strings as an input you can use string padding. Look here: Padding Strings in the .NET Framework
You can write some method (or extension method):
string AppendString(string str, int count, char filler, bool fromStart)
{
return fromStart ? str.PadLeft(count, filler) : str.PadRight(count, filler);
}
I think this code should work for you.
Console.WriteLine("Please type in your company number!");
string companyNr = Console.ReadLine();
Console.WriteLine("Type a filler");
string filler= Convert.ToChar(Console.ReadLine());
string fill = companyNr.PadLeft(20,filler);
// or use string fill = companyNr.PadRight(20,filler);
Welcome to StackOverflow. I am also a beginner :)
int fixedLength = 20;
string mockupInput = "bladjiea";
string filler = "-";
While(mockupInput.Length < fixedLength)
{
mockupInput += filler;
}
This is easy beginner code that should work.
Lets make this a contest on who will write most beautiful code:
I'll start with the most trivial, brute method XD.
If you have the number:
int fillLength = 20 - companyNr.Length; //for example, 20 chars total.
You can fill a StringBuilder in a loop:
var sb = new StringBuilder()
for (int c = 0; c < fillLength; c++)
sb.Append(filler);
string result = companyNr + sb.ToString();
Related
Super new to C# apologize upfront. My goal is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Numbers can be from 1 to 9. So 1 will be the first word (not 0).
My plan of attack is to split the string, having one variable of int data-type (int lookingForNum) and the other variable turning that into a String data-type(string stringLookingForNum), then for each loop over the array looking to see if any elements contain string stringLookingForNum, if they do I add it to an emptry string variable, lastly add 1 to int variable lookingForNum. My issue seems to be with the if statement with the Contains method. It will not trigger the way I currently have it written. Hard coding in if (word.Contains("1")) will trigger that code block but running it as written below will not trigger the if statement.Please can anyone tell my WHY!?!? I console.log stringLookingForNum and it is for sure a string data type "1"
This noobie would appreciate any help. Thanks!
string testA = "is2 Thi1s T4est 3a"; //--> "Thi1s is2 3a T4est"
string[] arrayTestA = testA.Split(' ');
string finalString = string.Empty;
int lookingForNum = 1; //Int32
foreach (string word in arrayTestA){
string stringLookingForNum = lookingForNum.ToString();
//Don't understand why Contains is not working as expected here)
if (word.Contains(stringLookingForNum)){
finalString = finalString + $"{word} ";
}
lookingForNum++;
}
you need this - look for the string with 1, the look for the string with 2 etc. Thats not what you are doing
you look at the first string and see if it contains one
then look at the second one and see if it contains 2
....
int lookingForNum = 1;
while(true){ // till the end
string stringLookingForNum = lookingForNum.ToString();
bool found = false;
foreach (string word in arrayTestA){
if (word.Contains(stringLookingForNum)){
finalString = finalString + $"{word} ";
found = true;
break;
}
}
if(!found) break;
lookingForNum++;
}
To sort you should simply use OrderBy, and since you need to sort by number inside a word - just Find and extract a number from a string
string testA = "is2 Thi1s T4est 3a";
var result = testA.Split().OrderBy(word =>
Int32.Parse(Regex.Match(word, #"\d+").Value));
Console.WriteLine(string.Join(" ", result));
Messing around with C# logic, trying to build a program where the user inputs a string, and then has the option to decide which letter is removed from said string.
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
Console.WriteLine("please enter letters you would like removed");
char removedLetters = Convert.ToChar(Console.ReadLine());
foreach (char letter in input)
{
Console.WriteLine(input.Replace(removedLetters,' ').ToLower());
}
This works, but not entirely. I will get rid of characters, but only when written in a specific way that corresponds with the original input.
e.g helloworld -> remove l = he owor d
but helloworld -> remove elo = failure.
Can someone share some knowledge? Really trying to get better at logic, happy i got this far just need bit of guidance.
Cheers,
Andy
Expanding on Jasen's comment from earlier something like this ...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
List<char> input_array = input.ToList();
Console.WriteLine("please enter letters you would like removed");
string removedLetters = Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
for (int k = 0; k < remove_array.Count(); k++)
{ input_array.RemoveAll(r=>r== remove_array[k]); }
Console.WriteLine(new string(input_array.ToArray()));
Again, using Linq, in this case RemoveAll, to automate the heavy lifting. I have not tested how efficient these are, they are quick and simple solutions not necessarily the most efficient.
Not sure how you want to handle duplicates but C# has an Except operator that works on Arrays. So convert both strings to an array and something like this should work...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
char[] input_array = input.ToArray();
Console.WriteLine("please enter letters you would like removed");
string removedLetters =Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
char[] leftover_array = input_array.Except(remove_array).ToArray();
Console.WriteLine(new string(leftover_array));
I've been using C# String.Format for formatting numbers before like this (in this example I simply want to insert a space):
String.Format("{0:### ###}", 123456);
output:
"123 456"
In this particular case, the number is a string. My first thought was to simply parse it to a number, but it makes no sense in the context, and there must be a prettier way.
Following does not work, as ## looks for numbers
String.Format("{0:### ###}", "123456");
output:
"123456"
What is the string equivalent to # when formatting? The awesomeness of String.Format is still fairly new to me.
You have to parse the string to a number first.
int number = int.Parse("123456");
String.Format("{0:### ###}", number);
of course you could also use string methods but that's not as reliable and less safe:
string strNumber = "123456";
String.Format("{0} {1}", strNumber.Remove(3), strNumber.Substring(3));
As Heinzi pointed out, you can not have format specifier for string arguments.
So, instead of String.Format, you may use following:
string myNum="123456";
myNum=myNum.Insert(3," ");
Not very beautiful, and the extra work might outweigh the gains, but if the input is a string on that format, you could do:
var str = "123456";
var result = String.Format("{0} {1}", str.Substring(0,3), str.Substring(3));
string is not a IFormattable
Console.WriteLine("123456" is IFormattable); // False
Console.WriteLine(21321 is IFormattable); // True
No point to supply a format if the argument is not IFormattable only way is to convert your string to int or long
We're doing string manipulation, so we could always use a regex.
Adapted slightly from here:
class MyClass
{
static void Main(string[] args)
{
string sInput, sRegex;
// The string to search.
sInput = "123456789";
// The regular expression.
sRegex = "[0-9][0-9][0-9]";
Regex r = new Regex(sRegex);
MyClass c = new MyClass();
// Assign the replace method to the MatchEvaluator delegate.
MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceNums);
// Replace matched characters using the delegate method.
sInput = r.Replace(sInput, myEvaluator);
// Write out the modified string.
Console.WriteLine(sInput);
}
public string ReplaceNums(Match m)
// Replace each Regex match with match + " "
{
return m.ToString()+" ";
}
}
How's that?
It's been ages since I used C# and I can't test, but this may work as a one-liner which may be "neater" if you only need it once:
sInput = Regex("[0-9][0-9][0-9]").Replace(sInput,MatchEvaluator(Match m => m.ToString()+" "));
There is no way to do what you want unless you parse the string first.
Based on your comments, you only really need a simple formatting so you are better off just implementing a small helper method and thats it. (IMHO it's not really a good idea to parse the string if it isn't logically a number; you can't really be sure that in the future the input string might not be a number at all.
I'd go for something similar to:
public static string Group(this string s, int groupSize = 3, char groupSeparator = ' ')
{
var formattedIdentifierBuilder = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (i != 0 && (s.Length - i) % groupSize == 0)
{
formattedIdentifierBuilder.Append(groupSeparator);
}
formattedIdentifierBuilder.Append(s[i]);
}
return formattedIdentifierBuilder.ToString();
}
EDIT: Generalized to generic grouping size and group separator.
The problem is that # is a Digit placeholder and it is specific to numeric formatting only. Hence, you can't use this on strings.
Either parse the string to a numeric, so the formatting rules apply, or use other methods to split the string in two.
string.Format("{0:### ###}", int.Parse("123456"));
string containsCharacter = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(containsCharacter).Length - 1;
I originally pulled this code off another person's question's answer but it doesn't seem to work with text boxes.
Errors I'm getting:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Argument 1: cannot convert from 'string' to 'char[]'
I prefer to fix this code rather than use other things like LINQ but I would accept it if there isn't a way to fix this code.
You could iterate through the characters
string value = "BANANA";
int x = 0;
foreach (char c in value)
{
if (c == 'A')
x++;
}
string containsCharacter = "t";
string testString = "test string contains certain characters";
int count = testString.Count(x => x.ToString() == containsCharacter);
This example will return 6.
The Split version you are using expects a character as input. This is the version for strings:
string containsText = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(new string[]{containsText}, StringSplitOptions.None).Length - 1;
With this code, count will be: 1 if textBox1.Text includes "test", 6 if it contains "t", etc. That is, it can deal with any string (whose length might be one, as a single character, or as big as required).
You can call ToCharArray on the string to make it a char[], like this:
int count = testString.Split(containsCharacter.ToCharArray()).Length - 1;
Since Split takes characters as a param, you could rewrite this by listing the characters being counted directly, as follows:
int count = testString.Split(',', ';', '-').Length - 1;
"this string. contains. 3. dots".Split(new[] {"."}, StringSplitOptions.None).Count() - 1
Edit:
Upon Reading your code more carefully I suggest you do this, you should rephrase your question to
"Check the number of occurences of a certain string in Another string":
string containsString = "this";
string test = "thisisateststringthisisateststring";
var matches = Regex.Matches(test,containsString).Count;
matches is 2!
My initial post answers your actual question "occurrences of a certain character in a string":
string test = "thisisateststring";
int count = test.Count(w => w == 'i');
Count is 3!
Suppose I have a string "011100011".
Now I need to find another string by adding the adjacent digits of this string, like the output string should be "123210122".
How do I split each characters in the string and manipulate them?
The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.
But can you suggest some simpler methods?
Here's a solution which uses some LINQ plus dahlbyk's idea:
string input = "011100011";
// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0";
var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
output += integers.Skip(i).Take(3).Sum();
}
// output is now "123210122"
Please note:
the code is not optimized. E.g. you might want to use a StringBuilder in the for loop.
What should happen if you have a '9' in the input string -> this might result in two digits in the output string.
Try converting the string to a character array and then subtract '0' from the char values to retrieve an integer value.
string input = "011100011";
int current;
for (int i = 0; i < input.Length; i ++)
{
current = int.Parse(input[i]);
// do something with current...
}