how to get rid of Too many characters in character literal? [duplicate] - c#

This question already has answers here:
"Too many characters in character literal error"
(6 answers)
Closed 6 years ago.
I get the error Too many characters in character literal for the below code?how should I declare the buildserverlocation?
using System;
class Program
{
static void Main(string[] args)
{
string buildServerLocation = #'\\Location\builds682\INTEGRATION\ABC1234.QSC.0.0-000000025-P-1';
char delimiterChars = '\\';
string[] serverString = buildServerLocation.Split(delimiterChars);
string serverName = serverString[1] + ".company.com";
Console.WriteLine("build server name is " + serverName);
}
}

This needs to be a string, but you've used the ' syntax, which is valid only for a single character:
string buildServerLocation = #'\\snowcone\builds682\INTEGRATION\IPQ8064.ILQ.5.0-000000025-P-1';
should be
string buildServerLocation = #"\\snowcone\builds682\INTEGRATION\IPQ8064.ILQ.5.0-000000025-P-1";
This declaration is correct by itself, but you then go on to pass it to split. That's legal -- thanks Jeppe -- but it would be better to make it clear that this is an array with a single char:
char delimiterChars = '\\';
should be
char[] delimiterChars = { '\\' };
But the larger problem is that none of this is correct. If you're splitting up a path, use a class dedicated to extracting data from paths rather than rolling your own.
Also, not a super great idea from a security perspective to be posting paths of your internal servers on a public site.

This line is your problem:
char delimiterChars = '\\';
You can only have one character in a char literal. What you need to use as delimiters either needs to be a string denoted by using quotations marks.
string delimiterChars = "\\";
Note: This will work with little other editing, as string.Split() has an overload that takes a string. You just need to define its second parameter, which in this case could be null.

Related

What's the difference between {"::"} and "::"? [duplicate]

This question already has answers here:
Split string requires array declaration
(2 answers)
Closed 2 years ago.
I have some code like this:
string[] separator = {"::"};
var seperatedCardString = currentCard.Name.Split(
separator, StringSplitOptions.RemoveEmptyEntries);
Can someone explain to me exactly what's happening with this and why there is a need to use {"::"}. My separator is :: so I am confused as to why it's coded the way it is.
The code line string[] separator = {"::"}; is initializing array separator. This syntax to initialize the array is referred as Implicitly Typed Arrays.
Currently your code using Split(String[], StringSplitOptions) method of string to split the string where the first arg is type of string array. If you have only one seperator (i.e. ::) then you can use the overload method Split(String, StringSplitOptions) by below code
string separator = "::";
var seperatedCardString = currentCard.Name.Split(
separator, StringSplitOptions.RemoveEmptyEntries);
Check all the overload of string Split method at here

Find and move unknown word between particular characters in the string C#

I'm trying to find and move unknown word between particular characters in the string in C#.
Example:
// this is a string from the file
begining of the string - " TASK PERS partdata pd_Test_05:=["Call_Test_05","Test_05","T_ROB1",1,0,"",""];" - end of the string.
// I insert that string inside the string[] lines.
// I need to found and seperate word "Test_05" from that string.
It looks like you might be able to do something like this:
List<string> test = yourString.Split(',').ToList<string>();
string finalProduct = test[1];
At this point, your string would look like "Test_05". Just replace the quotation marks with C#'s replace or Regex replace them.
Its hard to know how to give an answer, we dont know what makes Test_05 the particular target.
As a general guide you can either use Regular expressions if the target string matches a pattern. You might find this site useful http://regexstorm.net/
Or you can use string operations like IndexOf (search for a given string in a string), Substring (slice out a piece of a string), Replace,...
Thanks GMR516.
I finished with 'Trim.
string[] lines = File.ReadAllLines("testFile.mod");
List<string> test = lines[0].Split(',').ToList<string>();
string finalProduct = test[1].Remove(1, 0);
Console.WriteLine($"Before trim: {finalProduct}");
char[] charsToTrim = { '*', ' ', '\'', '"' };
// Trim method can remove any characters from specified string
string result = finalProduct.Trim(charsToTrim);
Console.WriteLine($"After Trim: {result}");

Splitting string with dots and spaces [duplicate]

This question already has answers here:
Regex split string but keep separators
(2 answers)
Closed 7 years ago.
Let's say I have the following string: "This is a test. Haha.". I want to split it so that it becomes these there lines:
Hey.
This is a test.
Haha.
(Note that the space after the dot is preserved).
I tried to split the string using the Split method, and split by the dot, but it returns 3 new strings with the space before the string, and it removes the dots. I want to keep the space after the dot and keep the space.
How can I achieve this?
EDIT: I found a workaround, but I'm sure there's a simpler way:
string a = "Hey. This is a test. Haha.";
string[] splitted = a.Split('.');
foreach(string b in splitted)
{
if (b.Length < 3)
{
continue;
}
string f = b.Remove(0, 1);
Console.WriteLine(f + ". ");
}
I can't test this but due to the post of Darin Dimitrov :
string input = "Hey. This is a test. Haha.";
string result = input.Replace(". ", ".\n");

Using string.ToUpper on substring

Have an assignment to allow a user to input a word in C# and then display that word with the first and third characters changed to uppercase. Code follows:
namespace Capitalizer
{
class Program
{
static void Main(string[] args)
{
string text = Console.ReadLine();
char[] delimiterChars = { ' ' };
string[] words = text.Split(delimiterChars);
string Upper = text.ToUpper();
Console.WriteLine(Upper);
Console.ReadKey();
}
}
}
This of course generates the entire word in uppercase, which is not what I want. I can't seem to make text.ToUpper(0,2) work, and even then that'd capitalize the first three letters. Only solution I can think of now that would make the word appear on one line (and I don't know if it works) is to move the capitalized letters and lowercase letters into a character array and try to get that to print all values in a modified order.
The simplest way I can think of to address your exact question as described — to convert to upper case the first and third characters of the input — would be something like the following:
StringBuilder sb = new StringBuilder(text);
sb[0] = char.ToUpper(sb[0]);
sb[2] = char.ToUpper(sb[2]);
text = sb.ToString();
The StringBuilder class is essentially a mutable string object, so when doing these kinds of operations is the most fluid way to approach the problem, as it provides the most straightforward conversions to and from, as well as the full range of string operations. Changing individual characters is easy in many data structures, but insertions, deletions, appending, formatting, etc. all also come with StringBuilder, so it's a good habit to use that versus other approaches.
But frankly, it's hard to see how that's a useful operation. I can't help but wonder if you have stated the requirements incorrectly and there's something more to this question than is seen here.
You could use LINQ:
var upperCaseIndices = new[] { 0, 2 };
var message = "hello";
var newMessage = new string(message.Select((c, i) =>
upperCaseIndices.Contains(i) ? Char.ToUpper(c) : c).ToArray());
Here is how it works. message.Select (inline LINQ query) selects characters from message one by one and passes into selector function:
upperCaseIndices.Contains(i) ? Char.ToUpper(c) : c
written as C# ?: shorthand syntax for if. It reads as "If index is present in the array, then select upper case character. Otherwise select character as is."
(c, i) => condition
is a lambda expression. See also:
Understand Lambda Expressions in 3 minutes
The rest is very simple - represent result as array of characters (.ToArray()), and create a new string based off that (new string(...)).
Only solution I can think of now that would make the word appear on one line (and I don't know if it works) is to move the capitalized letters and lowercase letters into a character array and try to get that to print all values in a modified order.
That seems a lot more complicated than necessary. Once you have a character array, you can simply change the elements of that character array. In a separate function, it would look something like
string MakeFirstAndThirdCharacterUppercase(string word) {
var chars = word.ToCharArray();
chars[0] = chars[0].ToUpper();
chars[2] = chars[2].ToUpper();
return new string(chars);
}
My simple solution:
string text = Console.ReadLine();
char[] delimiterChars = { ' ' };
string[] words = text.Split(delimiterChars);
foreach (string s in words)
{
char[] chars = s.ToCharArray();
chars[0] = char.ToUpper(chars[0]);
if (chars.Length > 2)
{
chars[2] = char.ToUpper(chars[2]);
}
Console.Write(new string(chars));
Console.Write(' ');
}
Console.ReadKey();

C# string.replace to remove illegal characters [duplicate]

This question already has answers here:
How to remove illegal characters from path and filenames?
(30 answers)
Closed 9 years ago.
I'm working on a program that reads files and saves pieces of them according to their column's title. Some of those titles have illegal characters for file names, so i've written this piece of code to handle those issues.
string headerfile = saveDir + "\\" + tVS.Nodes[r].Text.Replace("\"", "").Replace
("/","").Replace(":"," -").Replace(">","(Greater Than)") + ".csv";
Is there a nicer way of doing this where i don't have 4 .Replace()? or is there some sort of built in illegal character remover i don't know of?
Thanks!
EDIT: It does not need to replace the characters with anything specific. A blank space is sufficient.
Regular expressions are generally a good way to do that, but not when you're replacing every character with something different. You might consider replacing them all with the same thing, and just using System.IO.Path.GetInvalidFileNameChars().
string filename = tVS.Nodes[r].Text;
foreach(char c in System.IO.Path.GetInvalidFileNameChars()) {
filename = filename.Replace(c, '_');
}
System.IO.Path.GetInvalidFileNameChars() has all the invalid characters.
Here's a sample method:
public static string SanitizeFileName(string fileName, char replacementChar = '_')
{
var blackList = new HashSet<char>(System.IO.Path.GetInvalidFileNameChars());
var output = fileName.ToCharArray();
for (int i = 0, ln = output.Length; i < ln; i++)
{
if (blackList.Contains(output[i]))
{
output[i] = replacementChar;
}
}
return new String(output);
}
Have a look at Regex.Replace here, it will do everything you desire when it comes to stripping out characters individually. Selective replacement of other strings may be trickier.
string charsToRemove = #"\/:";TODO complete this list
string filename;
string pattern = string.format("[{0}]", Regex.Escape(charsToRemove));
Regex.Replace(filename, pattern, "");
If you just want to remove illegal chars, rather than replacing them with something else you can use this.

Categories

Resources