Issue with \ and \\ when calling String Split() - c#-4.0

I am trying to split some string on the basis of newline character '\n'
I have this delimiter stored in resx file as:
Name: RecordDelimiter
Value: \n
When I retrieve this value from .resx file it is always returned as '\n' and
split function does not return accurate results.
However when I try with string "\n", it's working fine
Here is my code -
private static void GetRecords()
{
string recordDelimiter = #"\n";
string recordDelimiter1 = "\n"; // only this returns correct result
string recordDelimiter2 = ResourceFile.RecordDelimiter; //from resx file, returns \\n :-(
string recordDelimiter3 = ResourceFile.RecordDelimiter.Replace("\\", #"\"); //try replacing \\n with \n
string fileOutput = "aaa, bbb, ccc\naaa1, bbb1, ccc1\naaa2, bbb2, ccc2";
string[] records = fileOutput.Split(new string[] { recordDelimiter }, StringSplitOptions.None);
string[] records1 = fileOutput.Split(new string[] { recordDelimiter1 }, StringSplitOptions.None);
string[] records2 = fileOutput.Split(new string[] { recordDelimiter2 }, StringSplitOptions.None);
string[] records3 = fileOutput.Split(new string[] { recordDelimiter3 }, StringSplitOptions.None);
int recordCount = records.Count(); //returns 1
int recordCount1 = records1.Count(); //returns 3 -- only this returns correct result
int recordCount2 = records2.Count(); //returns 1
int recordCount3 = records3.Count(); //returns 1
}
I want to keep the delimiter in resx file.
Can anyone please guide if I am missing something?
Thank you!

The reason your second method is the only one returning the correct result is that it is the only one where the delimiter is the new line character. "\n" is just a representation of the newline character in C#, and #"\n" is the literal string of a slash followed by the letter n. In other words #"\n" != "\n".
So if you wanted to store the delimiter character in resx, you would need to show us the code of how you are storing it there. Currently it seems to just be stord as a literal string, and not the actual control characters.
One (very rough) fix would be to take the string from the Resources and call .Replace(#"\n", "\n") depending on what exactly is stored in the file. I will update my answer if/when I find a better solution, or once you have updated your question.
EDIT:
Ok, found a somewhat gimmicky solution. The core problem is how do you write just \n, correct? Well, I made a test project, with a textbox and the following code:
this.textBox1.Text = "1\n2";
Fire up this project, select all of the text in the textbox, and copy to clipboard. Then go to your real project's resources, and paste the value from your clipboard. Then carefully delete the numbers from around the control character. And there you go, \n control character in a resource string. (The reason for the numbers was that it wasn't possible to select only the control character from the textbox.)

Related

Apex - remove special characters from a string except for ''+"

In Apex, I want to remove all the special characters in a string except for "+". This string is actually a phone number. I have done the following.
String sampleText = '+44 597/58-31-30';
sampleText = sampleText.replaceAll('\\D','');
System.debug(sampleText);
So, what it prints is 44597583130.
But I want to keep the sign + as it is represents 00.
Can someone help me with this ?
Possible solutions
String sampleText = '+44 597/58-31-30';
// exclude all characters which you want to keep
System.debug(sampleText.replaceAll('[^\\+|\\d]',''));
// list explicitly each char which must be replaced
System.debug(sampleText.replaceAll('/|-| ',''));
Output in both case will be the same
|DEBUG| +44597583130
|DEBUG| +44597583130
Edit
String sampleText = '+0032 +497/+59-31-40';
System.debug(sampleText.replaceAll('(?!^\\+)[^\\d]',''));
|DEBUG|+0032497593140

How do I make a new line in swift

Is there a way to have a way to make a new line in swift like "\n" for java?
var example: String = "Hello World \n This is a new line"
You should be able to use \n inside a Swift string, and it should work as expected, creating a newline character. You will want to remove the space after the \n for proper formatting like so:
var example: String = "Hello World \nThis is a new line"
Which, if printed to the console, should become:
Hello World
This is a new line
However, there are some other considerations to make depending on how you will be using this string, such as:
If you are setting it to a UILabel's text property, make sure that the UILabel's numberOfLines = 0, which allows for infinite lines.
In some networking use cases, use \r\n instead, which is the Windows newline.
Edit: You said you're using a UITextField, but it does not support multiple lines. You must use a UITextView.
Also useful:
let multiLineString = """
Line One
Line Two
Line Three
"""
Makes the code read more understandable
Allows copy pasting
You can use the following code;
var example: String = "Hello World \r\n This is a new line"
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1
Phone Number: output of string2
"\n" is not working everywhere!
For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")
There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).
using this extension:
extension CharacterSet {
var allCharacters: [Character] {
var result: [Character] = []
for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
result.append(Character(uniChar))
}
}
}
return result
}
}
you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:
let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
print("Hello World \(newLine) This is a new line")
}
Then store the one you tested and worked everywhere and use it anywhere.
Note that you can't relay on the index of the character set. It may change.
But most of the times "\n" just works as expected.

C++ Replacing non-alpha/apostrophe with spaces in a string

I am reading in a text file and parsing the words into a map to count numbers of occurrences of each word on each line. I am required to ignore all non-alphabetic chars (punctuation, digits, white space, etc) except for apostrophes. I can figure out how to delete all of these characters using the following code, but that causes incorrect words, like "one-two" comes out as "onetwo", which should be two words, "one" and "two".
Instead, I am trying to now replace all of these values with spaces instead of simply deleting, but can't figure out how to do this. I figured the replace-if algorithm would be a good algorithm to use, but can't figure out the proper syntax to accomplish this. C++11 is fine. Any suggestions?
Sample output would be the following:
"first second" = "first" and "second"
"one-two" = "one" and "two"
"last.First" = "last" and "first"
"you're" = "you're"
"great! A" = "great" and "A"
// What I initially used to delete non-alpha and white space (apostrophe's not working currently, though)
// Read file one line at a time
while (getline(text, line)){
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> word){
word.erase(remove_if(word.begin(), word.end(), my_predicate), word.end());
++tokens[word][linenum];
}
++linenum;
}
bool my_predicate(char c){
return c == '\'' || !isalpha(c); // This line's not working properly for apostrophe's yet
}
bool my_predicate(char c){
return c == '\'' || !isalpha(c);
}
Here you're writing that you want to remove the char if it is and apostrophe or if it is not an alphabetical character.
Since you want to replace these, you should use std::replace_if() :
std::replace_if(std::begin(word), std::end(word), my_predicate, ' ');
And you should correct your predicate too :
return !isalpha(c) && c != '\'';
You could use std::replace_if to pre-process the input line before sending it to the istringstream. This will also simplify your inner loop.
while (getline(text, line)){
replace_if(line.begin(), line.end(), my_predicate, ' ');
istringstream iss(line);
// Parse line on white space, storing values into tokens map
while (iss >> word){
++tokens[word][linenum];
}
++linenum;
}

Blackberry Java replace char \n

I have an example string get from XML, contains: Hello\nWorld\n\nClick\nHere.\nThanks.
And then i want to replace the \n char with space char.
Already try using string replace, string substring, string indexOf. But cannot detect the \n char, iam trying using '\r\n' to detect, but didnt work.
String hello = "Hello\nWorld\n\nClick\nHere.\nThanks.";
String afterReplace = hello.replace('\n', ' ');
But still cannot remove/replace the \n with space.
Anyone can help me?
Thanks a lot.
If I understand correctly you have a string which when printed shows the \n characters and does not actually skip a line.
Hello\nWorld\n\nClick\nHere.\nThanks. would be represented in code by:
String s = "Hello\\nWorld\\n\\nClick\\nHere.\\nThanks."
Now s is equal to what you would obtain from your XML.
Try this:
String afterReplace = hello.replace('\\n', ' ');

Remove a character from a string without knowing its position

I want to remove a character ('.') from a string without knowing its position.
For example.
string test = "4.000";
But the '.' will always change.
Thanks!
If you only want to remove the first occurrence of that character:
string newString = test.Remove(test.IndexOf(".", 1));
If you want to remove all occurrences of that character:
string newString = test.Replace(".", "");
Use String.Replace.
string stringToReplace = ".";
string test = "4.000";
test = test.Replace(stringToReplace, "");

Resources