Trim () functions are not unfamiliar to everyone. Many languages support this function. It is also very common when processing strings (such as form processing). Its function is to remove spaces at both ends of the string, and return a new string. Below we write two implementations of trim () for your reference.
C language:
#include "stdio.h"char * trim(char *str){int _len = strlen(str);int back_index = _len-1;char *temp_str = str;if(str == NULL || _len <= 0)return NULL;while(*temp_str == ' '){temp_str++;}while(*(str + back_index) == ' '){back_index--;};temp_str[back_index] = 0;return temp_str;}main(){char str[] = " hello world ";char * new_str;printf("---");printf("%s",str);printf("---\n");new_str = trim(str);printf("---");printf("%s",new_str);printf("---\n");}
Test results:
Java version:
Public class mytrim {public static void main (string [] ARGs) {string STR = "Hello World"; system. out. print ("="); system. out. print (STR); system. out. println ("="); STR = runmytrim (STR); system. out. print ("="); system. out. print (STR); system. out. println ("=");} Private Static string runmytrim (string Str) {If (null = STR | "". equals (STR) {system. out. println ("the string is empty"); return NULL;} Char [] cs = Str. tochararray (); int _ start = 0; int _ end = cs. length-1; while (CS [_ start] = '') {_ start ++;} while (CS [_ end] = '') {_ end --;} return Str. substring (_ start, _ end + 1 );}}
Test results:
========================================================== ========================================================== ============================
Author: Nash _ Welcome to repost. sharing with others is the source of progress!
Reprinted Please retain the original address: http://blog.csdn.net/nash_/article/details/8209469
========================================================== ========================================================== ==============================