How do I make a new line in swift - string

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.

Related

How to remove text character values from string on flutter

I would like to retrieve only the number values from a string on flutter without keeping the text hardcoded using replaceAll, the text can be anything but the number part of it has to be retrieved from it.
e.g.
String text = "Hello your number is: 1234";
String numberProvided = '1234'; // needs to be extracted from String text
print("The number provided is :" + numberProvided);
Like I said, the text characters shouldn't be hardcoded into the application, let me know if it is possible, thanks!
Use the simple regular expression
print(text.replaceAll(RegExp("[a-zA-Z:\s]"), ""));
Try below code hope its help to you. refer replaceAll method here
void main() {
String text = "Hello your number is: 1234567890";
var aString = text.replaceAll(RegExp(r'[^0-9]'), '');
var aInteger = int.parse(aString);
print(
"The number provided is :" + aInteger.toString(),
);
}
Your Output:
The number provided is :1234567890

Kotlin - How to trim all leading spaces from a multiline string?

String.trim() does not work for strings built using buildString. For example,
val s = buildString {
append("{")
append('\n')
append(" ".repeat(5))
append("hello")
append(" ".repeat(7))
append("world")
append("}")
}
println(s.trim())
This prints
{
hello world}
but I need it to print
{
hello
world
}
How can I trim indent without writing my own trim method?
trim() only removes whitespaces from the beginning and end of a whole string, not per-line. You can remove spaces from each line with:
s.lineSequence()
.map { it.trim() }
.joinToString("\n")
Please note that as a side effect, above code converts all line endings to LF ("\n"). You can replace "\n" with "\r\n" or "\r" to get different results. To preserve line endings exactly as they were in the original string, we would need a more complicated solution.
One liner:
s.lines().joinToString(transform = String::trim, separator = "\n")
You could use a regular expression to trim leading whitespace:
val s = buildString {
append("{")
append('\n')
append(" ".repeat(5))
append("hello\n")
append(" ".repeat(7))
append("world\n")
append("}")
}
println(s.replace(Regex("""^\s+""", RegexOption.MULTILINE), ""))
Output:
{
hello
world
}

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;
}

Issue with \ and \\ when calling String Split()

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.)

What characters can I use to quote this ruby string?

I'm embedding JRuby in Java, because I need to call some Ruby methods with Java strings as arguments. The thing is, I'm calling the methods like this:
String text = ""; // this can span over multiple lines, and will contain ruby code
Ruby ruby = Ruby.newInstance();
RubyRuntimeAdapter adapter = JavaEmbedUtils.newRuntimeAdapter();
String rubyCode = "require \"myscript\"\n" +
"str = build_string(%q~"+text+"~)\n"+
"str";
IRubyObject object = adapter.eval(ruby, codeFormat);
The thing is, I don't know what strings I can use as delimiters, because if the ruby code I'm sending to build_string will contain ruby code. Right know I'm using ~,but I think this could break my code. What characters can I use as delimiters to make sure my code will work no matter what the ruby code is?
use the heredoc format:
"require \"myscript\"\n" +
"str = build_string(<<'THISSHOUDLNTBE'\n" + text + "\nTHISSHOULDNTBE\n)\n"+
"str";
this however assumes you won't have "THISSHOULDNTBE" on a separate line in the input.
Since string text contain contain any character, there is no character left to use for quotation escaping like the ~ you're using now. You would still need to escape the tilde in string text in java and append that one to the string you're building.
Something like (untested, not a Java guru):
String rubyCode = "require \"myscript\"\n" +
"str = build_string(%q~" + text.replaceAll("~", "\\~") + "~)\n"+
"str";

Resources