从字符串的开头或末尾删除空格,但不 [英] Remove spaces from a string, but not at the beginning or end

查看:182
本文介绍了从字符串的开头或末尾删除空格,但不的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符串在C,不是从最终删除空格,也没有开始的时候,在一个字符串只是多个空格

I am trying to remove spaces from a string in C, not from the end, nor the beginning, just multiple spaces in a string

例如

hello  everyone this     is a test

有打招呼,每个人之间的两个空格,从这个5个空格的。最后,我想从5从2和4 1空间,让每一个缝隙有1个空间完全吻合。有意义吗?

has two spaces between hello and everyone, and five spaces from this to is. Ultimately I would want to remove 1 space from the 2 and 4 from the 5, so every gap has 1 space exactly. Make sense?

这就是我要做的事情:


  • 创建一个指针,在单元1字符它指向字符串[0]。

  • create a pointer, point it to the string at element 1 char[0].

通过字符串的长度做一个for循环

do a for loop through the length of the string

然后我的逻辑是,如果我在指针[i]为一个空间,我在元素指针[I + 1]空间,然后做一下

then my logic is, if my pointer at [i] is a space and my pointer at element [i+1] space then to do something

我不太清楚什么是从这里很好的解决,铭记我不会使用任何pre-内置函数。没有人有任何想法?

I am not quite sure what would be a good solution from here, bearing in mind I won't be using any pre-built functions. Does anyone have any ideas?

推荐答案

一个办法是做在原地。循环通过从开始字符串结束。存储写指针和读指针。每个循环由一个写入指针和读出指针前进。当遇到一个空间转移它作为正常但随后循环读指针每次递增,直到非空间被发现(或字符串的末尾,很明显)。在最后不要忘记加上'\\ 0',你现在有没有空间相同的字符串。

One way is to do it in-place. Loop through the string from the beginning to end. store a write pointer and a read pointer. Each loop the write pointer and read pointer advances by one. When you encounter a space transfer it as normal but then loop the read pointer incrementing each time until a non-space is found (Or the end of the string, obviously). Don't forget to add a '\0' at the end and you now have the same string without the spaces.

这篇关于从字符串的开头或末尾删除空格,但不的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆