Trim () implementation methods

Source: Internet
Author: User

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

========================================================== ========================================================== ==============================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.