Using .Net 2.0 how can i check if a multi line text box has only newline characters?
No text at all, but only \n, \r, etc..?
if (Regex.IsMatch(#"^[\r\n]+$", text))
You can use String.IsNullOrWhiteSpace method.
if(!string.IsNullOrWhiteSpace(TextBox1.Text))
{
}
Here is the source of IsNullOrWhiteSpace -
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null)
return true;
for (int index = 0; index < value.Length; ++index)
{
if (!char.IsWhiteSpace(value[index]))
return false;
}
return true;
}
Have you tried replacing Environment.NewLine with nothing?
For example,
Dim tbLen as Integer = tb.Text.Length() 'returns 2 for 1 return character
Dim tbLenFiltered As Integer = tb.Text.Replace(Environment.NewLine, String.Empty).Length() 'returns 0 for 1 return character
Related
I am retrieving data from a DB table using SqlDataReader in ASP.net. I append the retrieved data in a string builder and after that, dump the contents of the string builder into a text file. My problem is that in that text file white spaces are showing up between one column and another ... How can I remove the excess white spaces from my text file?
Thanks in advance.
1. Text.Trim();
2. Text.Replace(" ", string.empty);
private string process(string s)
{
int len = s.Length;
int current=0;
StringBuilder sb = new StringBuilder(len);
while (current < len-1)
{
if (!(s[current] == ' ' && s[current + 1] == ' ') &&
!(s[current] == '\n' && s[current + 1] == '\n')
)
{
sb.Append(s[current]);
}
current++;
}
return sb.ToString();
}
I must display very small values (capacitor) in a Flex-AdvancedDataGrid
I use spark.formatters.NumberFormatter.
If I use 3, 6 or 9 for fractionalDigits, everything is fine.
But if I use 12, because I need 12 digits after decimal separator, then the value is cut after 9 digits!
Is there a way to get more then 9 digits after separator.
Or is there a way to use a formatting like "4.7 E-12" (Must be E-9, E-12, E-15 and so on)
toPrecision and toFixed works fine up to 20 digits. Thats enough.
I will write a function on this base to get results like 4.7 E-12.
Thanks for the help
Jan
I created a custom pattern formatter class that allows you to specify how you want a string/number formatted using whatever symbols or structure you want. Depending on your requirements, this may help you. Feel free to modify this class as needed.
CustomPatternFormatter.as
package
{
import mx.formatters.Formatter;
public class CustomPatternFormatter extends Formatter
{
private static const VALID_PATTERN_CHARACTERS:String = "#,.-";
// Use # as a placeholder for a regular
// character in the input string.
// Then add other characters between the
// # symbol for the desired output format.
// ex. The pattern ##,##,##.## with input 12345678
// will output 12,34,56.78
public var formatPattern:String;
// If True, the input string must match the number
// of # characters in the formatPattern.
public var inputMustMatchPatternLength:Boolean;
//Constructor
public function CustomPatternFormatter()
{
super();
formatPattern = "";
inputMustMatchPatternLength = false;
}
// Override format().
override public function format(value:Object):String
{
// Reset error if it exists.
if (error)
error = null;
// If value is null, or empty String just return ""
// but treat it as an error for consistency.
// Users will ignore it anyway.
if (!value || (value is String && value == ""))
{
error = "Cannot convert an empty value";
return "";
}
// Check to see if the input value must match the format pattern
if (inputMustMatchPatternLength && String(value).length != countOccurrences(formatPattern, "#"))
{
error = "The input value length does not match the format pattern length.";
return "";
}
// If the value is valid, format the string.
var fStrLen:int = 0;
var letter:String;
var n:int;
var i:int;
var v:int;
// Make sure the formatString is valid.
n = formatPattern.length;
for (i = 0; i < n; i++)
{
letter = formatPattern.charAt(i);
if (letter == "#")
{
fStrLen++;
}
else if (VALID_PATTERN_CHARACTERS.indexOf(letter) == -1)
{
error = "You can only use the following symbols in the formatPattern: " + VALID_PATTERN_CHARACTERS;
return "";
}
}
var returnString:String = "";
var vStr:String = String(value).replace(".", "").split("").reverse().join("");
var fArr:Array = formatPattern.split("").reverse();
var fChar:String;
// Format the string
for (v = 0; v < vStr.length; v++) { if (fArr.length > 0)
{
do
{
fChar = fArr.shift();
if (fChar != "#")
returnString += fChar;
} while (fChar != "#" && fArr.length > 0);
}
returnString += vStr.charAt(v);
}
// Return the formatted string
return returnString.split("").reverse().join("");
}
protected function countOccurrences(str:String, char:String):int
{
var count:int = 0;
for (var i:int=0; i < str.length; i++)
{
if (str.charAt(i) == char)
{
count++;
}
}
return count;
}
}
}
I need to remove spaces from the end of a string. How can I do that?
Example: if string is "Hello " it must become "Hello"
Taken from this answer here: https://stackoverflow.com/a/5691567/251012
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return #"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
Another solution involves creating mutable string:
//make mutable string
NSMutableString *stringToTrim = [#" i needz trim " mutableCopy];
//pass it by reference to CFStringTrimSpace
CFStringTrimWhiteSpace((__bridge CFMutableStringRef) stringToTrim);
//stringToTrim is now "i needz trim"
Here you go...
- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for(i = [strtoremove length]; i >0; i--) {
NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
if(![charSet characterIsMember:charBuffer[i - 1]]) {
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:
NSString *oneTwoThree = #" TestString ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];
resultString will then have no spaces at the end.
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//for remove whitespace and new line character
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet punctuationCharacterSet]];
//for remove characters in punctuation category
There are many other CharacterSets. Check it yourself as per your requirement.
To remove whitespace from only the beginning and end of a string in Swift:
Swift 3
string.trimmingCharacters(in: .whitespacesAndNewlines)
Previous Swift Versions
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))
Swift version
Only trims spaces at the end of the String:
private func removingSpacesAtTheEndOfAString(var str: String) -> String {
var i: Int = countElements(str) - 1, j: Int = i
while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
--i
}
return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}
Trims spaces on both sides of the String:
var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
This will remove only the trailing characters of your choice.
func trimRight(theString: String, charSet: NSCharacterSet) -> String {
var newString = theString
while String(newString.characters.last).rangeOfCharacterFromSet(charSet) != nil {
newString = String(newString.characters.dropLast())
}
return newString
}
In Swift
To trim space & newline from both side of the String:
var url: String = "\n http://example.com/xyz.mp4 "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
A simple solution to only trim one end instead of both ends in Objective-C:
#implementation NSString (category)
/// trims the characters at the end
- (NSString *)stringByTrimmingSuffixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = self.length;
while (i > 0 && [characterSet characterIsMember:[self characterAtIndex:i - 1]]) {
i--;
}
return [self substringToIndex:i];
}
#end
And a symmetrical utility for trimming the beginning only:
#implementation NSString (category)
/// trims the characters at the beginning
- (NSString *)stringByTrimmingPrefixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = 0;
while (i < self.length && [characterSet characterIsMember:[self characterAtIndex:i]]) {
i++;
}
return [self substringFromIndex:i];
}
#end
To trim all trailing whitespace characters (I'm guessing that is actually your intent), the following is a pretty clean & concise way to do it.
Swift 5:
let trimmedString = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
Objective-C:
NSString *trimmedString = [string stringByReplacingOccurrencesOfString:#"\\s+$" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
One line, with a dash of regex.
The solution is described here: How to remove whitespace from right end of NSString?
Add the following categories to NSString:
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return #"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingTrailingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
And you use it as such:
[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]
I came up with this function, which basically behaves similarly to one in the answer by Alex:
-(NSString*)trimLastSpace:(NSString*)str{
int i = str.length - 1;
for (; i >= 0 && [str characterAtIndex:i] == ' '; i--);
return [str substringToIndex:i + 1];
}
whitespaceCharacterSet besides space itself includes also tab character, which in my case could not appear. So i guess a plain comparison could suffice.
let string = " Test Trimmed String "
For Removing white Space and New line use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
For Removing only Spaces from string use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)
NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:#" " withString:#""];
}
how can i convert a string to a Decimal(10,2) in C#?
Take a look at Decimal.TryParse, especially if the string is coming from a user.
You'll want to use TryParse if there's any chance the string cannot be converted to a Decimal. TryParse allows you to test if the conversion will work without throwing an Exception.
You got to be careful with that, because some cultures uses dots as a thousands separator and comma as a decimal separator.
My proposition for a secure string to decimal converstion:
public static decimal parseDecimal(string value)
{
value = value.Replace(" ", "");
if (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
{
value = value.Replace(".", ",");
}
else
{
value = value.Replace(",", ".");
}
string[] splited = value.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (splited.Length > 2)
{
string r = "";
for (int i = 0; i < splited.Length; i++)
{
if (i == splited.Length - 1)
r += System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
r += splited[i];
}
value = r;
}
return decimal.Parse(value);
}
The loop is in case that string contains both, decimal and thousand separator
Try:
string test = "123";
decimal test2 = Convert.ToDecimal(test);
//decimal test2 = Decimal.Parse(test);
//decimal test2;
// if (decimal.TryParse(test, out result))
//{ //valid }
//else
//{ //Exception }
labelConverted.Text = test2.toString();
Decimal Examples
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
Regards
I have some issues with Arduino about how to match text.
I have:
String tmp = +CLIP: "+37011111111",145,"",,"",0
And I am trying to match:
if (tmp.startsWith("+CLIP:")) {
mySerial.println("ATH0");
}
But this is not working, and I have no idea why.
I tried substring, but the result is the same. I don't know how to use it or nothing happens.
Where is the error?
bool Contains(String s, String search) {
int max = s.length() - search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i) == search) return true; // or i
}
return false; //or -1
}
Otherwise you could simply do:
if (readString.indexOf("+CLIP:") >=0)
I'd also recommend visiting:
https://www.arduino.cc/en/Reference/String
I modified the code from gotnull. Thanks to him to put me on the track.
I just limited the search string, otherwise the substring function was not returning always the correct answer (when substrign was not ending the string). Because substring search always to the end of the string.
int StringContains(String s, String search) {
int max = s.length() - search.length();
int lgsearch = search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i, i + lgsearch) == search) return i;
}
return -1;
}
//+CLIP: "43660417XXXX",145,"",0,"",0
if (strstr(command.c_str(), "+CLIP:")) { //Someone is calling
GSM.print(F("ATA\n\r"));
Number = command.substring(command.indexOf('"') + 1);
Number = Number.substring(0, Number.indexOf('"'));
//Serial.println(Number);
} //End of if +CLIP:
This is how I'm doing it. Hope it helps.
if (tmp.startsWith(String("+CLIP:"))) {
mySerial.println("ATH0");
}
You can't put the string with quotes only you need to cast the variable :)